golang package log

package main

import (
    "log"
    "os"
)

var logger *log.Logger

func main() {
    file,err := os.OpenFile("test.log",os.O_APPEND|os.O_CREATE,666)
    if err != nil {
        log.Fatalln("fail to create test.log file!")
    }
    defer file.Close()
    logger = log.New(file,"",log.LstdFlags|log.Lshortfile) // 日志文件格式:log包含时间及文件行数
    log.Println("输出日志到命令行终端")
    logger.Println("将日志写入文件")

    logger.SetFlags(log.LstdFlags | log.Lshortfile) // 设置日志格式

    log.Panicln("在命令行终端输出panic,并中断程序执行")
    logger.Panicln("在日志文件中写入panic,并中断程序执行")

    log.Fatal("在命令行终端输出日志并执行os.exit(1)")
    logger.Fatal("在日志文件中写入日志并执行os.exit(1)")
}

Logger结构体所有字段都是私有的,提供了一个工厂函数获取结构体实例

// New creates a new Logger. The out variable sets the
// destination to which log data will be written.
// The prefix appears at the beginning of each generated log line.
// The flag argument defines the logging properties.
func New(out io.Writer,prefix string,flag int) *Logger {
   return &Logger{out: out,prefix: prefix,flag: flag}
}

flag参数的常量

const (
   Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
   Ltime                         // the time in the local time zone: 01:23:23
   Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
   Llongfile                     // full file name and line number: /a/b/c/d.go:23
   Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
   LUTC                          // if Ldate or Ltime is set,use UTC rather than the local time zone
   LstdFlags     = Ldate | Ltime // initial values for the standard logger
)

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1&#160;Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...