本文整理汇总了Golang中log.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: SetLogLevel
func SetLogLevel(level string) error {
resetLogLevel()
switch level {
case "trace":
break
case "debug":
Trace = log.New(ioutil.Discard, "TRC ", log.Ldate|log.Ltime)
case "info":
Trace = log.New(ioutil.Discard, "TRC ", log.Ldate|log.Ltime)
Debug = log.New(ioutil.Discard, "DBG ", log.Ldate|log.Ltime)
case "warning":
Trace = log.New(ioutil.Discard, "TRC ", log.Ldate|log.Ltime)
Debug = log.New(ioutil.Discard, "DBG ", log.Ldate|log.Ltime)
Info = log.New(ioutil.Discard, "INF ", log.Ldate|log.Ltime)
case "error":
Trace = log.New(ioutil.Discard, "TRC ", log.Ldate|log.Ltime)
Debug = log.New(ioutil.Discard, "DBG ", log.Ldate|log.Ltime)
Info = log.New(ioutil.Discard, "INF ", log.Ldate|log.Ltime)
Warning = log.New(ioutil.Discard, "WRN ", log.Ldate|log.Ltime)
default:
return errors.New(fmt.Sprintf("Invalid log level: %s", level))
}
return nil
}
示例2: NewLogger
func NewLogger(prefix string, level LogLevel) *Logger {
godbc.Require(level >= 0, level)
godbc.Require(level <= LEVEL_DEBUG, level)
l := &Logger{}
if level == LEVEL_NOLOG {
l.level = LEVEL_DEBUG
} else {
l.level = level
}
l.critlog = log.New(stderr, prefix+" CRITICAL ", log.LstdFlags)
l.errorlog = log.New(stderr, prefix+" ERROR ", log.LstdFlags)
l.warninglog = log.New(stdout, prefix+" WARNING ", log.LstdFlags)
l.infolog = log.New(stdout, prefix+" INFO ", log.LstdFlags)
l.debuglog = log.New(stdout, prefix+" DEBUG ", log.LstdFlags)
godbc.Ensure(l.critlog != nil)
godbc.Ensure(l.errorlog != nil)
godbc.Ensure(l.warninglog != nil)
godbc.Ensure(l.infolog != nil)
godbc.Ensure(l.debuglog != nil)
return l
}
示例3: ErrLogOn
func ErrLogOn(on bool) {
if on {
errlog = l.New(os.Stdout, "ERROR: starfish backend: ", l.Ldate|l.Ltime)
} else {
errlog = l.New(ioutil.Discard, "ERROR: starfish backend: ", l.Ldate|l.Ltime)
}
}
示例4: initLogs
func (DS *MainSearch) initLogs(logdir string) {
// open logs
DS.logDir = logdir
os.Mkdir(DS.logDir, os.ModePerm)
tmpF0, err5 := os.Create(DS.logDir + "main:err.log")
if err5 != nil {
log.Fatal("couldn't create errs log", err5)
}
DS.errLogBuf = bufio.NewWriter(tmpF0)
DS.errLogBuf.Flush()
DS.errLog = log.New(DS.errLogBuf, "", log.LstdFlags)
tmpF1, err1 := os.Create(DS.logDir + "main:main.log")
if err1 != nil {
log.Fatal("couldn't create main log", err1)
}
DS.mainLogBuf = bufio.NewWriter(tmpF1)
DS.mainLogBuf.Flush()
DS.mainLog = log.New(DS.mainLogBuf, "", log.LstdFlags)
tmpF2, err2 := os.Create(DS.logDir + "main:eqns.log")
if err2 != nil {
log.Fatal("couldn't create eqns log", err2)
}
DS.eqnsLogBuf = bufio.NewWriter(tmpF2)
DS.eqnsLogBuf.Flush()
DS.eqnsLog = log.New(DS.eqnsLogBuf, "", log.LstdFlags)
}
示例5: init
func (k *KLog) init() (err error) {
if len(k.name) == 0 {
return errors.New("not init.")
}
day := time.Now().Format("20060102")
if k.day == day {
return nil
}
k.Close()
file := filepath.Clean(k.path + "/" + k.name + day + ".log")
if !filepath.IsAbs(file) {
file = filepath.Clean(ProcessPath() + "/" + file)
}
path := filepath.Dir(file)
if err = os.MkdirAll(path, 0777); err != nil {
return err
}
k.logFile, err = os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
if err != nil {
return err
}
if os.Stdout == nil || k.bstdout == false {
k.log = log.New(k.logFile, k.prefix, log.Ldate|log.Ltime)
} else {
k.wr = io.MultiWriter(os.Stdout, k.logFile)
k.log = log.New(k.wr, k.prefix, log.Ldate|log.Ltime)
}
k.day = day
return nil
}
示例6: init
func init() {
flag.Parse()
if *debug {
logger = log.New(os.Stdout, "godev", log.LstdFlags)
} else {
logger = log.New(ioutil.Discard, "godev", log.LstdFlags)
}
goroot = runtime.GOROOT() + string(os.PathSeparator)
dirs := build.Default.SrcDirs()
for i := len(dirs) - 1; i >= 0; i-- {
srcDir := dirs[i]
if !strings.HasPrefix(srcDir, goroot) {
srcDirs = append(srcDirs, srcDir)
}
if bundle_root_dir == "" {
_, err := os.Stat(srcDir + "/github.com/sirnewton01/godev/bundles")
if err == nil {
bundle_root_dir = srcDir + "/github.com/sirnewton01/godev/bundles"
break
}
}
}
// Try the location provided by the srcdir flag
if bundle_root_dir == "" && *godev_src_dir != "" {
_, err := os.Stat(*godev_src_dir + "/bundles")
if err == nil {
bundle_root_dir = *godev_src_dir + "/bundles"
}
}
if bundle_root_dir == "" {
log.Fatal("GOPATH variable doesn't contain the godev source.\nEither add the location to the godev source to your GOPATH or set the srcdir flag to the location.")
}
if os.Getenv("GOHOST") != "" {
hostName = os.Getenv("GOHOST")
certFile = os.Getenv("GOCERTFILE")
keyFile = os.Getenv("GOKEYFILE")
// If the host name is not loopback then we must use a secure connection
// with certificatns
if certFile == "" || keyFile == "" {
log.Fatal("When using a public port a certificate file (GOCERTFILE) and key file (GOKEYFILE) environment variables must be provided to secure the connection.")
}
// Initialize the random magic key for this session
rand.Seed(time.Now().UTC().UnixNano())
magicKey = strconv.FormatInt(rand.Int63(), 16)
}
}
示例7: main
func main() {
// fmt.Printf("OAEP Encrypted [%s] to \n[%x]\n", string(plain_text), encrypted)
// fmt.Printf("OAEP Decrypted [%x] to \n[%s]\n", encrypted, decrypted)
//letters := []string{"a", "b", "c", "d"}
//barrenoid.TestRsa()
file, err := os.OpenFile("barrenslog.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
chkError(err)
multi := io.MultiWriter(file, os.Stdout)
dbgMsg = log.New(multi, "INFO: ", log.Ldate|log.Ltime)
errMsg = log.New(multi, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
RoomList = make(map[string]*Room)
var generalChatClients []*Client
generalChatRoom := Room{"GeneralChat", generalChatClients}
RoomList["GeneralChat"] = &generalChatRoom
listener, err := net.Listen("tcp", PORT)
chkError(err)
dbgMsg.Println("Server started on port", PORT)
//Main server loop, accept incoming connections
for {
conn, err := listener.Accept()
chkError(err)
dbgMsg.Println("Connection accepted from: ", conn.RemoteAddr())
go ClientHandler(conn)
}
}
示例8: initLoggers
func initLoggers() {
logFatal = log.New(os.Stderr, "FATAL: ", log.Lshortfile)
errorHandle := os.Stderr
infoHandle := ioutil.Discard
benchmarkHandle := ioutil.Discard
if *logfile != "" {
lgf, err := os.OpenFile(*logfile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
logFatal.Fatalf("Error opening log file (%s): %v\n", *logfile, err)
}
errorHandle = lgf
infoHandle = lgf
benchmarkHandle = lgf
}
if *benchmark != "" {
prf, err := os.OpenFile(*benchmark, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
logFatal.Fatalf("Error opening benchmark file (%s): %v\n", *benchmark, err)
}
benchmarkHandle = prf
}
if *verbose {
errorHandle = os.Stderr
infoHandle = os.Stderr
benchmarkHandle = os.Stderr
}
logError = log.New(errorHandle, "ERROR: ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
logInfo = log.New(infoHandle, "INFO: ", log.Ldate|log.Lmicroseconds)
logBenchmark = log.New(benchmarkHandle, "BENCHMARK: ", log.Ldate|log.Lmicroseconds)
}
示例9: TestLoggerMiscBytes0
/*
Test Logger with a zero Byte Message, a corner case. This is merely
to demonstrate the basics of log output when a logger is set for the
connection.
*/
func TestLoggerMiscBytes0(t *testing.T) {
ll := log.New(os.Stdout, "TLM01 ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
// Write phase
n, _ := openConn(t)
ch := check11(TEST_HEADERS)
conn, _ := Connect(n, ch)
conn.SetLogger(ll)
//
ms := "" // No data
d := tdest("/queue/logger.zero.byte.msg")
sh := Headers{HK_DESTINATION, d}
e := conn.Send(sh, ms)
if e != nil {
t.Fatalf("Expected nil error, got [%v]\n", e)
}
//
_ = conn.Disconnect(empty_headers)
_ = closeConn(t, n)
// Read phase
n, _ = openConn(t)
ch = check11(TEST_HEADERS)
conn, _ = Connect(n, ch)
ll = log.New(os.Stdout, "TLM02 ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
conn.SetLogger(ll)
//
sbh := sh.Add(HK_ID, d)
sc, e := conn.Subscribe(sbh)
if e != nil {
t.Fatalf("Expected no subscribe error, got [%v]\n", e)
}
if sc == nil {
t.Fatalf("Expected subscribe channel, got [nil]\n")
}
// Read MessageData
var md MessageData
select {
case md = <-sc:
case md = <-conn.MessageData:
t.Fatalf("read channel error: expected [nil], got: [%v]\n",
md.Message.Command)
}
if md.Error != nil {
t.Fatalf("Expected no message data error, got [%v]\n", md.Error)
}
// The real tests here
if len(md.Message.Body) != 0 {
t.Fatalf("Expected body length 0, got [%v]\n", len(md.Message.Body))
}
if string(md.Message.Body) != ms {
t.Fatalf("Expected [%v], got [%v]\n", ms, string(md.Message.Body))
}
//
_ = conn.Disconnect(empty_headers)
_ = closeConn(t, n)
}
示例10: TestFmtReadError
// A read error whilst reading a fmt chunk should result in an error
func TestFmtReadError(t *testing.T) {
description := "A read error whilst reading a fmt chunk should result in an error"
// Prepare a decoder to use
var d decoder
d.audio = new(audio.Audio)
// Only log the chunk contents if verbose is enabled
if testing.Verbose() {
d.logger = log.New(os.Stdout, "", 0)
} else {
d.logger = log.New(ioutil.Discard, "", 0)
}
// Read an empty chunk to force a read error
d.reader = bytes.NewReader([]byte{})
err := d.readFmtChunk()
// Reading the chunk should have thrown an error
if err == nil {
t.Errorf("FAIL Test %v: %v:\nWant: error\nActual: nil", len(fmtChunkTests)+1, description)
} else {
t.Logf("PASS Test %v: %v:\nWant: error\nActual: %v", len(fmtChunkTests)+1, description, err.Error())
}
}
示例11: init
func init() {
c.ERROR = log.New(os.Stderr, "", log.LstdFlags)
c.WARN = log.New(os.Stderr, "", log.LstdFlags)
c.INFO = log.New(os.Stderr, "", log.LstdFlags)
c.TRACE = log.New(os.Stderr, "", log.LstdFlags)
}
示例12: NewLogger
func NewLogger(out io.Writer) *Logger {
info := log.New(out, "INFO: ", log.Ldate|log.Ltime)
warn := log.New(out, "WARN: ", log.Ldate|log.Ltime)
alert := log.New(out, "ALERT: ", log.Ldate|log.Ltime|log.LUTC)
return &Logger{info: info, warn: warn, alert: alert}
}
示例13: main
func main() {
verbose := false
flag.BoolVar(&verbose, "v", false, "verbose logging")
port := "3333"
flag.StringVar(&port, "port", "3333", "port")
host := "localhost"
flag.StringVar(&host, "host", "localhost", "host")
flag.Parse()
logger := log.New(os.Stdin, "["+host+":"+port+"] ", log.LstdFlags)
if !verbose {
logger = log.New(new(NullWriter), "", 0)
}
server := server.New("http://"+host+":"+port, logger)
logger.Printf("Starting")
http.Handle("/", server.Handler())
err := http.ListenAndServe(host+":"+port, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
示例14: main
// Remember Exit(0) is success, Exit(1) is failure
func main() {
flag.Var(&slaveList, "control", "list of ip:port addresses to control")
flag.Parse()
if len(*testUrl) == 0 {
flag.Usage()
os.Exit(1)
}
if len(slaveList) > 0 && *listen != 0 {
fmt.Fprintf(os.Stderr, "You can't have both --listen and --control flags")
flag.Usage()
os.Exit(1)
}
rand.Seed(time.Now().Unix())
// set up logging
logWriter, err := os.OpenFile(*logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
println(err)
os.Exit(1)
}
log.SetOutput(logWriter)
TRACE = log.New(ioutil.Discard,
"TRACE: ",
log.Ldate|log.Ltime|log.Lshortfile)
INFO = log.New(logWriter,
"INFO: ",
log.Ldate|log.Ltime|log.Lshortfile)
ERROR = log.New(logWriter,
"ERROR: ",
log.Ldate|log.Ltime|log.Lshortfile)
INFO.Println("beginning run")
os.Exit(realMain())
}
示例15: NewLogger
// NewLogger creates a new logger
func NewLogger(stdout string, stderr string) (logger *Logger, err error) {
var (
stderrWriter = os.Stderr
stdoutWriter = os.Stdout
toClose []closeable
)
if stderr != "" {
if stderrWriter, err = os.OpenFile(stderr, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil {
return
}
toClose = append(toClose, stderrWriter)
}
if stdout != "" {
if stdoutWriter, err = os.OpenFile(stdout, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil {
return
}
toClose = append(toClose, stderrWriter)
}
logger = &Logger{
stderr: log.New(stderrWriter, "ERROR ", log.LstdFlags|log.Lshortfile),
stdout: log.New(stdoutWriter, "INFO ", log.LstdFlags|log.Lshortfile),
toClose: toClose,
}
return
}