有什么方法可以使用golang std库格式化日志(如下所述)?

  1. ​Feb 1, 2018 at 3:04:05pm (UTC) | This is log message

  2. 2018-02-01T15:04:05Z | This is log message

I found the next formats in go src: https://github.com/golang/go/blob/master/src/log/log.go#L37 But it seems I couldn't manage to do it by using only those ones..

Two options here:

use log.SetOutput to set a custom writer.

Or use the fmt package instead to just print to stdout or elsewhere - the stdlib log package doesn't do much and it's pretty easy to create your own log package which outputs with custom time format(s) to stdout (or a log file). For example here is such a package in a few lines:

package log

import (
    "fmt"
    "time"
)

var TimeFormat = "2006-02-01T15:04:05Z"

func Printf(format string, args ...interface{}) {
    format = fmt.Sprintf("%s %s", time.Now().Format(TimeFormat), format)
    fmt.Printf(format, args...)
}

I'd recommend doing this yourself if you have specific needs, and just output to stdout with fmt.Printf. You don't really need a third party log package.

https://play.golang.org/p/iPeuGjQqEf4

You can use log.SetOutput(...) with an argument writer that prints entries using your desired format (such as the builtin RFC3999 or one of your choice), for example:

const timeFormat = time.RFC3339

type logWriter struct{}

func (lw *logWriter) Write(bs []byte) (int, error) {
  return fmt.Print(time.Now().UTC().Format(timeFormat), " | ", string(bs))
}

func main() {
  log.SetFlags(0)               // Omit default prefixes.
  log.SetOutput(new(logWriter)) // Use our custom writer.

  log.Printf("Hello, %s!", "World")
  // 2018-09-18T14:50:40Z | Hello, World!
}

You can change the timestamp by using a different format, e.g.:

const timeFormat = "Jan 2, 2006 at 3:04:05pm (UTC)"

// ...
  log.Printf("Hello, %s!", "World")
  // Sep 18, 2018 at 2:52:26pm (UTC) | Hello, World!

https://play.golang.org/p/hPCn3MflkgQ Here is an answer. You should deal with Writer interface and create new Log by using it