本文整理汇总了Golang中log.Logger.Println方法的典型用法代码示例。如果您正苦于以下问题:Golang Logger.Println方法的具体用法?Golang Logger.Println怎么用?Golang Logger.Println使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类log.Logger
的用法示例。
在下文中一共展示了Logger.Println方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: acceptConn
func acceptConn(conn net.Conn, l log.Logger) {
l.Println("Success: Connection accepted from ", conn.RemoteAddr())
fmt.Println("Success: Connection accepted from ", conn.RemoteAddr())
for {
data := make([]byte, 4096)
n, err := conn.Read(data)
if err != nil {
fmt.Println("Error while reading from connection: ", err.Error())
return
}
fmt.Println("Number of bytes read: ", n)
convertData(data, n)
}
// Handle timeout?!
/*
err := conn.Close()
if err != nil {
l.Println(err.Error())
} else {
l.Println("Connection closed.")
fmt.Println("Connection closed.")
}*/
}
示例2: print
// pring write message into logger. If console is enabled, write into too
func (l Logger) print(loggerElement *log.Logger, message ...interface{}) {
data := append([]interface{}{getInfo()}, message...)
loggerElement.Println(data...)
if l.writeConsole {
log.Println(data...)
}
}
示例3: ZmqPubSubProxy
// ZmqPubSubProxy Implements a many-to-many device on a zmq PUB-SUB connection
func ZmqPubSubProxy(host string, portIn int, portOut int, logger *log.Logger) {
xsub, _ := zmq.NewSocket(zmq.SUB)
xpub, _ := zmq.NewSocket(zmq.PUB)
defer xsub.Close()
defer xpub.Close()
addrIn := fmt.Sprintf("tcp://*:%d", portIn)
addrOut := fmt.Sprintf("tcp://*:%d", portOut)
logger.Println("ZMQ XSUB on", addrIn)
xsub.Bind(addrIn)
xsub.SetSubscribe("")
logger.Println("ZMQ XPUB on", addrOut)
xpub.Bind(addrOut)
poller := zmq.NewPoller()
poller.Add(xsub, zmq.POLLIN)
for {
// keep looping
sockets, _ := poller.Poll(5 * time.Second)
for _, socket := range sockets {
switch s := socket.Socket; s {
case xsub:
ZmqSendMulti(xpub, ZmqRecvMulti(s))
}
}
}
}
示例4: RegisterData
func RegisterData(params martini.Params, l *log.Logger, db *sql.DB) (int, string) {
key := params["key"]
value := params["value"]
l.Println(key, value)
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
for i := 0; i < 10; i++ {
_, err = stmt.Exec(i, fmt.Sprintf("[%s = %s] ねぷねぷのぷりん%03d", key, value, i))
if err != nil {
log.Fatal(err)
}
}
tx.Commit()
return 200, "Hello!" + value
}
示例5: Register
func Register(consulURL string, logger *log.Logger, service *Service) error {
var httpresponse *http.Response
var err error
var buf []byte
buf, err = json.Marshal(service)
if err != nil {
log.Println(err.Error())
return err
}
body := bytes.NewBuffer(buf)
log.Println(body.String())
httpresponse, err = http.Post(consulURL+REGISTER, "application/json", body)
if err != nil {
logger.Println(err.Error())
return err
}
logger.Printf("register status code: %d\n", httpresponse.StatusCode)
if httpresponse.StatusCode != 200 {
return errors.New("register: invalid status code " + httpresponse.Status)
}
return err
}
示例6: deleteUnneededFiles
func deleteUnneededFiles(srpcClient *srpc.Client, subFS *filesystem.FileSystem,
imgFS *filesystem.FileSystem, logger *log.Logger) bool {
startTime := showStart("compute early files to delete")
pathsToDelete := make([]string, 0)
imgHashToInodesTable := imgFS.HashToInodesTable()
imgFilenameToInodeTable := imgFS.FilenameToInodeTable()
for pathname, inum := range subFS.FilenameToInodeTable() {
if inode, ok := subFS.InodeTable[inum].(*filesystem.RegularInode); ok {
if inode.Size > 0 {
if _, ok := imgHashToInodesTable[inode.Hash]; !ok {
pathsToDelete = append(pathsToDelete, pathname)
}
} else {
if _, ok := imgFilenameToInodeTable[pathname]; !ok {
pathsToDelete = append(pathsToDelete, pathname)
}
}
}
}
showTimeTaken(startTime)
if len(pathsToDelete) < 1 {
return false
}
updateRequest := sub.UpdateRequest{
Wait: true,
PathsToDelete: pathsToDelete}
var updateReply sub.UpdateResponse
startTime = showStart("Subd.Update() for early files to delete")
err := client.CallUpdate(srpcClient, updateRequest, &updateReply)
showTimeTaken(startTime)
if err != nil {
logger.Println(err)
}
return true
}
示例7: xmit
// Goroutine to handle transmitting packets from one socket to another:
func (c *conn) xmit(r io.Reader, w io.Writer, stop chan bool, logger *log.Logger) {
buffer := make([]byte, buffer_size)
for {
// 5 second read deadline so that we don't get lots of CLOSE_WAIT sockets:
r.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Millisecond * time.Duration(5000)))
rn, err := r.Read(buffer)
if err != nil {
if c.handleError(err, logger) {
continue
} else {
break
}
}
_, err = w.Write(buffer[:rn])
if err != nil {
if c.handleError(err, logger) {
continue
} else {
break
}
}
}
stop <- true
if verbose {
logger.Println("stopped")
}
}
示例8: PurgeURL
func PurgeURL(url string, log *log.Logger) error {
timeout := time.Duration(2 * time.Second)
client := &http.Client{
Timeout: timeout,
}
// Invalidate the file
req, err := http.NewRequest("PURGE", url, nil)
if err != nil {
log.Println("Unable to purge " + url + ": " + err.Error())
return err
}
resp, err := client.Do(req)
if err == nil {
defer resp.Body.Close()
}
if err != nil {
log.Println("Unable to purge " + url + ": " + err.Error())
return err
}
log.Println("Purging " + url + ": " + resp.Status)
return nil
}
示例9: doSnapshot
func doSnapshot(logger *log.Logger, params martini.Params, r render.Render) {
lang := params["language"]
// levelDBへ保存
level, err := leveldb.Open("snapshot", &db.Options{})
if err != nil {
r.Error(400)
}
defer level.Close()
key := createSnapshotKey(lang, time.Now())
logger.Println("key: ", key)
if _, err := level.Get([]byte(key), &db.ReadOptions{}); err != nil {
res, err := http.Get(fmt.Sprintf(gitHubStarURL, lang))
if err != nil {
r.Error(400)
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
r.Error(400)
}
if err := level.Set([]byte(key), data, &db.WriteOptions{}); err != nil {
r.Error(400)
}
}
r.JSON(200, nil)
}
示例10: NewContext
func NewContext(
localStoragePath string,
args []string,
logger *log.Logger,
fatal *log.Logger,
) (c G5CLIExecutionContext) {
l := local.New(localStoragePath)
if !l.IsPersisted() {
logger.Println("No locally cached data. Enhance...")
if err := g5hub.PopulateLocalStorage(l); err != nil {
fatal.Printf(err.Error() + "\n")
os.Exit(1)
}
l.Persist()
}
if l.ShouldNag() {
l.LastNagged = time.Now()
l.Persist()
layout := "Mon, 01/02/06"
s := l.LastUpdated.Format(layout)
logger.Printf("Your last update was %v. You should consider running the update command. I'll nag you again soon.\n", s)
}
return G5CLIExecutionContext{
LocalStorage: l,
Args: args,
Logger: logger,
Fatal: fatal,
Heroku: CLIHerokuExecutor{SuccessLogger: logger, ErrorLogger: fatal},
}
}
示例11: waitForNotifyEvents
func waitForNotifyEvents(watcher *fsnotify.Watcher, pathname string,
channel chan<- io.ReadCloser, logger *log.Logger) {
if file, err := os.Open(pathname); err == nil {
channel <- file
}
for {
select {
case event, ok := <-watcher.Event:
if !ok {
return
}
if event.Name != pathname {
continue
}
if file, err := os.Open(pathname); err != nil {
if os.IsNotExist(err) {
continue
}
if logger != nil {
logger.Printf("Error opening file: %s: %s\n", pathname, err)
}
} else {
channel <- file
}
case err, ok := <-watcher.Error:
if !ok {
return
}
logger.Println("Error with watcher:", err)
}
}
}
示例12: PostIdeaHandler
func PostIdeaHandler(req *http.Request, render render.Render, log *log.Logger) {
log.Println("Receive post data.")
name := req.FormValue("name")
email := req.FormValue("email")
link := req.FormValue("link")
content := req.FormValue("content")
log.Println("Name: " + name)
log.Println("Email: " + email)
log.Println("Link: " + link)
log.Println("Content: " + content)
if len(name) == 0 {
render.JSON(400, map[string]interface{}{"error": 1, "message": "Empty name."})
return
}
if len(email) == 0 {
render.JSON(400, map[string]interface{}{"error": 2, "message": "Empty email."})
return
}
if len(content) == 0 {
render.JSON(400, map[string]interface{}{"error": 3, "message": "Empty content."})
return
}
AddIdea(name, email, link, content)
render.JSON(200, map[string]interface{}{"error": 0})
}
示例13: proberLoop
func (p *proberType) proberLoop(defaultProbeInterval uint, logger *log.Logger) {
// Set the initial probe interval to the global default, if less than the
// interval for this prober. The probe interval will be gradually increased
// until the target probe interval is reached. This gives faster probing at
// startup when higher resolution may be helpful, and then backs off.
probeInterval := time.Duration(defaultProbeInterval) * time.Second
if probeInterval > p.probeInterval {
probeInterval = p.probeInterval
}
for {
p.probeStartTime = time.Now()
if err := p.prober.Probe(); err != nil {
logger.Println(err)
}
probeDuration := time.Since(p.probeStartTime)
p.probeTimeDistribution.Add(probeDuration)
time.Sleep(probeInterval - probeDuration)
// Increase the probe interval until the interval for this prober is
// reached.
if probeInterval < p.probeInterval {
probeInterval += time.Duration(defaultProbeInterval) * time.Second
}
if probeInterval > p.probeInterval {
probeInterval = p.probeInterval
}
}
}
示例14: incomingEmail
func incomingEmail(tc *twilio.Client, req *http.Request, log *log.Logger) {
if err := verifyMailgunSig(
req.FormValue("token"),
req.FormValue("timestamp"),
req.FormValue("signature"),
); err != nil {
log.Println("Mailgun request verification failed:", err)
return
}
dkim := req.FormValue("X-Mailgun-Spf")
spf := req.FormValue("X-Mailgun-Dkim-Check-Result")
sender := req.FormValue("sender")
if dkim != "Pass" || spf != "Pass" || sender != emailTo {
log.Printf("Email verification failed: SPF: %s, DKIM: %s, addr: %s", spf, dkim, sender)
return
}
params := twilio.MessageParams{Body: req.FormValue("stripped-text")}
dest := strings.SplitN(req.FormValue("recipient"), "@", 2)[0]
_, _, err := tc.Messages.Send(smsFrom, dest, params)
if err != nil {
log.Println("SMS send failed:", err)
return
}
log.Println("SMS sent to", dest)
}
示例15: LockMetrics
func LockMetrics(logger *log.Logger, dbs []string, HOSTNAME string, dbConn *sql.DB) []Metric {
logger.Println("get lock metrics 3.1")
var metrics = make([]Metric, 0)
for i := 0; i < len(dbs); i++ {
metric := Metric{}
var lockCount int64
var lockType, lockMode string
err := dbConn.QueryRow("select locktype,mode, count(*) from pg_locks, pg_database where pg_locks.database = pg_database.oid and pg_database.datname = '"+dbs[i]+"' group by pg_locks.locktype, pg_locks.mode").Scan(&lockType, &lockMode, &lockCount)
if err != nil {
logger.Println("error: " + err.Error())
return metrics
}
metric.Hostname = HOSTNAME
metric.MetricName = "lock_count"
metric.Units = "count"
metric.Value = lockCount
metric.LockType = lockType
metric.LockMode = lockMode
metric.DatabaseName = dbs[i]
metrics = append(metrics, metric)
}
return metrics
}