golang中自带的有log包,但是功能并不能满足我们。很多人推荐seelog,我们今天一起学习下。

安装

go get github.com/cihub/seelog

快速开始

引用seelog wiki上的代码

1
2
3
4
5
6
package main
import log "github.com/cihub/seelog"
func () {
defer log.Flush()
log.Info("Hello from Seelog!")
}

这样就能在控制面板打印了,但是它是那么的丑陋!这里Info方法代表的是日志的级别,常用的有Trace, Debug, Info, Warn, Error, Critical 方法。
我们一般都会自定义格式等,seelog为我们提供了xml和代码两种方式来配置。
先看最简单的xml配置使用方法

1
2
3
4
5
<seelog>
<outputs>
<console />
</outputs>
</seelog>

在代码中读取配置文档

1
2
3
4
5
6
7
logger, err := seelog.LoggerFromConfigAsFile("./config/seelog.xml")
if err != nil {
log.Fatal(err)
}
seelog.ReplaceLogger(logger)
defer seelog.Flush()
seelog.Error("seelog from config xml")

这样我们就使用的默认的配置,将信息打印到控制面板,同样它是如此的丑陋!
我们可以在任何时候调用LoggerFromConfigAsFile,官网上有句英文很形象”Changing config on the fly”除了AsFile方法之外,还有LoggerFromConfigAsBytes’, ‘LoggerFromConfigAsString,但是本人还是配置文档可读性更好。
Flush方法很重要。一般的我们不会在main协程中写日志文档。logger应该异步并保持顺序的吞掉日志message放到队列中,而flush就是用来把队列中的数据写到文档中。在crash的时候也应该保证日志数据不会丢失,我们应该用defer语句来达到这个效果,并且在没有写日志操作之前就调用,这样我们后面就不用操心了。
在这里有个ReplaceLogger方法,我们来指定logger,类似的还有个UseLogger方法,前者会flush日志并关闭原来的logger,而后者只flush日志。

配置文档

先看下官网的示范配置文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<seelog type="asynctimer" asyncinterval="5000000" minlevel="debug" maxlevel="error">
<exceptions>
<exception funcpattern="*main.test*Something*" minlevel="info"/>
<exception filepattern="*main.go" minlevel="error"/>
</exceptions>
<outputs formatid="main">
<console/>

<splitter formatid="format1">
<file path="log.log"/>
<file path="log2.log"/>
</splitter>
<splitter formatid="format2">
<file path="log3.log"/>
<file path="log4.log"/>
</splitter>

<rollingfile formatid="someformat" type="size" filename="./log/roll.log" maxsize="100" maxrolls="5" />

<buffered formatid="testlevels" size="10000" flushperiod="1000">
<file path="./log/bufFileFlush.log"/>
</buffered>

<filter levels="error">
<file path="./log/error.log"/>
<smtp senderaddress="noreply-notification-service@none.org"
sendername="Automatic notification service"
hostname="mail.none.org"
hostport="587"
username="nns"
password="123">
<recipient address="john-smith@none.com"/>
<recipient address="hans-meier@none.com"/>
</smtp>
<conn net="tcp4" addr="server.address:5514" tls="true" insecureskipverify="true" />
</filter>

</outputs>
<formats>
<format id="main" format="%Date(2006 Jan 02/3:04:05.000000000 PM MST) [%Level] %Msg%n"/>
<format id="someformat" format="%Ns [%Level] %Msg%n"/>
<format id="testlevels" format="%Level %Lev %LEVEL %LEV %l %Msg%n"/>
<format id="usetags" format="&lt;msg&gt;%Msg&lt;/time&gt;"/>
<format id="format1" format="%Date/%Time [%LEV] %Msg%n"/>
<format id="format2" format="%File %FullPath %RelFile %Msg%n"/>
</formats>
</seelog>

我们并不必把所有的配置项都了解清楚,只需要根据我们的需求配置即可。

formart配置

日志格式是配置文档中最重要的之一

1
2
3
4
5
<formats>
<format id="common" format="[%LEV] %Msg"/>
<format id="critical" format="%Time %Date %RelFile %Func %Msg"/>
<format id="criticalemail" format="Critical error on our server!n %Time %Date %RelFile %Func %Msg nSent by Seelog"/>
</formats>

我们可以指定一个format,每个format都有一个唯一 大专栏  golang seelog使用的id方便在别的地方引用它,format属性就是格式了,我们可以指定颜色、日期及调用的地方等。以%开始,后跟特定的字符串

  • %Level log level (Trace, Debug, Info, Warn, Error, Critical)
  • %Lev short log level (Trc, Dbg, Inf, Wrn, Err, Crt)
  • %LEVEL capitalized log level (TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL)
  • %LEV short capitalized log level (TRC, DBG, INF, WRN, ERR, CRT)
  • %l super compact log level (t, d, i, w, e, c)
  • %Msg message text (string)
  • %FullPath full caller file path
  • %File caller filename only
  • %RelFile caller path relative to the application runtime directory
  • %Func caller function name
  • %FuncShort caller function name part after the last dot
  • %Line line number where logger was called
    Date and time
  • %Ns - time.Now().UnixNano()
  • %Date - shortcut for ‘2006-01-02’
  • %Time - shortcut for ‘15:04:05’
  • %Date(…) - date with format, specified in parentheses. Uses standard time.Format, so check http://golang.org/src/pkg/time/format.go for identifiers list. Use it like that: “%Date(2006-01-02)” (or any other format)
  • %UTCNs - time.Now().UTC().UnixNano()
  • %UTCDate - shortcut for ‘2006-01-02’ (UTC)
  • %UTCTime - shortcut for ‘15:04:05’ (UTC)
  • %UTCDate(…) - UTC date with format, specified in parentheses. Uses standard time.Format, so check http://golang.org/src/pkg/time/format.go for identifiers list. Use it like that: “%UTCDate(2006-01-02)” (or any other format)
    Special symbols
  • %EscN - terminal ANSI CSI n [;k] m escape. Check Colored output for details
  • %n - newline
  • %t - tab

    自定义formatter

    上面这些特殊规则基本都能满足我们的需求,如果想自定义规则要注册:

    1
    2
    3
    4
    5
    6
    7
    8
    func createMyFormatter(params string) seelog.FormatterFunc {
    fmt.Println(params)
    return func(message string, level seelog.LogLevel, context seelog.LogContextInterface) interface{} {
    return "hello"
    }
    }

    seelog.RegisterCustomFormatter("myFormat",createMyFormatter)

在配置文档中使用

1
2
3
<formats>
<format id="test" format="%myFormat(10) %Date %Time %LEV %RelFile %Line:%Msg%n"/>
</formats>

这样每次都会在日志钱加上”hello”

约束配置

约束是为了配置保存的日志级别的,分为全局约束和异常

  1. 全局约束
    全局约束是应用到整个应用的。可以在根节点配置,可以设置最大、最小级别,或者直接列举出所有支持的级别。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    <seelog minlevel="info" maxlevel="error">
    <seelog levels="trace,info,critical">
    ```
    2. 异常约束
    这个主要是指定特殊的方法或文档中使用异常级别,感觉用处不大,可以去官网看详情。
    ### Dispatchers and receivers
    seelog为我们提供了主流的接收方式:文档、控制面板、网络通道、邮件等。
    举个栗子:
    ```xml
    <seelog>
    <outputs>
    <splitter formatid="common">
    <console/>
    <file path="file.log"/>
    <conn addr="192.168.0.2:8123"/>
    </splitter>
    <filter levels="critical">
    <file path="critical.log" formatid="critical"/>
    <smtp formatid="criticalemail" senderaddress="noreply-notification-service@none.org" sendername="Automatic notification service" hostname="mail.none.org" hostport="587" username="nns" password="123">
    <recipient address="john-smith@none.com"/>
    <recipient address="hans-meier@none.com"/>
    </smtp>
    </filter>
    </outputs>
    <formats>
    <format id="common" format="[%LEV] %Msg"/>
    <format id="critical" format="%Time %Date %RelFile %Func %Msg"/>
    <format id="criticalemail" format="Critical error on our server!n %Time %Date %RelFile %Func %Msg nSent by Seelog"/>
    </formats>
    </seelog>

在这里我们配置输出信息,splitter把数据分为三个组,而filter根据日志级别分为了两个组。具体分组后的流向很容易明白,不再做解释。
问题来了:我们怎么知道接收者和分发的更多属性细节?且听我细细道来:

receivers细节

File writer

这个就比较简单了

1
2
3
4
5
<seelog>
<outputs>
<file path="log.log"/>
</outputs>
</seelog>

注意不要使用特殊符号作为文档名即可

Console writer

这个更简单

1
2
3
4
5
<seelog>
<outputs>
<console/>
</outputs>
</seelog>

Rolling file writer

通过这个节点我们在日期发生变化或者日志文档达到限制的时候切换另一个新的文档。下面是对属性的解释:

  1. filename 指定日志文档路径,当切换新的日志文档的时候,文档名会有一定格式后面会讲解到
  2. type “date”或者”size”
  3. namemode “postfix”, “prefix”文档名前缀或后缀格式
  4. maxrolls 最多的文档数目,当超过这个现在就回把原来的给删除掉
  5. 存档格式,当超过文档数目时可以指定存档格式”none”, “zip”, “gzip”。如果设置为”none”那么就会删除
  6. archivepath 日志存档的目录
  7. maxsize 当type为size类型是,每个文档最大的限制(单位是字节)
  8. datepattern 日志文档名的日期格式,type为date时有效
  9. fullname boolean型的值,是否设置当前日志文档就按过期格式命名

    Buffered writer

    顾名思义,先把数据存到内存中,当缓冲区满的时候再刷到文档中

    1
    2
    3
    <buffered size="10000" flushperiod="1000">
    <file path="bufFile.log"/>
    </buffered>

除了以上各种writer外还有邮件,网络这里暂时不讲了

自定义receiver

除了控制面板、文档、网络、邮件外,seelog还支持自定义接收者,但是比较复杂,如果有需求可以详细的看文档,此处暂不深究

总结

seelog功能的确很强大!

golang seelog使用的更多相关文章

  1. golang第三方日志包seelog配置文件详解

    开发任何项目,都离不开日志,配好自己的项目日志输出,往往是开发项目的前提.在golang中,seelog应该是比较有名的日志处理包了,功能非常强大,seelog官方文档 一.seelog主要功能下面我 ...

  2. Go语言(golang)开源项目大全

    转http://www.open-open.com/lib/view/open1396063913278.html内容目录Astronomy构建工具缓存云计算命令行选项解析器命令行工具压缩配置文件解析 ...

  3. [转]Go语言(golang)开源项目大全

    内容目录 Astronomy 构建工具 缓存 云计算 命令行选项解析器 命令行工具 压缩 配置文件解析器 控制台用户界面 加密 数据处理 数据结构 数据库和存储 开发工具 分布式/网格计算 文档 编辑 ...

  4. 在Go语言中记录log:seelog包

    前两周调bug调的吐血,虽然解决了但是还是挺浪费时间的.跟同事聊了聊,觉得我们现在项目中的日志记录太少了,导致出了问题不知道怎么下手,还得自己改代码记录日志,然后排查问题.这样如果将来还有bug的话还 ...

  5. Golang优秀开源项目汇总, 10大流行Go语言开源项目, golang 开源项目全集(golang/go/wiki/Projects), GitHub上优秀的Go开源项目

    Golang优秀开源项目汇总(持续更新...)我把这个汇总放在github上了, 后面更新也会在github上更新. https://github.com/hackstoic/golang-open- ...

  6. golang基础学习---log

    package main import ( "log" ) func init() { log.SetPrefix("TRACE: ") log.SetFlag ...

  7. Golang 异常/日志处理

    1.xerrors 异常 xerrors 包是一个非常棒的设计,不同于往常语言如java/php,因为go的errors只是一个string类型的映射,所以内存占用空间很少.这在golang的核心库和 ...

  8. golang web框架设计4:日志设计

    beego的日志设计思路来自于seelog,根据不同的level来记录日志,beego设计的日志是一个轻量级的,采用系统log.Logger接口,默认输出到os.Stdout,用户可以实现这个接口然后 ...

  9. 支持rotate和大小限制的golang log库

    支持大小限制和rotate的log库,还是很有必要的,前者让你不再操心磁盘被吃光,后者让查日志更方便. 但是在golang中没有太好的实现,看过一些开源的和自行实现的,都有几个不满意的地方,比如: 没 ...

随机推荐

  1. CommandNotFoundError: No command 'conda conda'.

    出现情形 当前conda版本:4.6.11 当使用git bash,无论是在vscode中,还是在桌面上打开bash,都会出现这个错误.但是在cmd中,就可以识别conda命令. 解决 该错误只在4. ...

  2. 问:为什么java是单继承,但却是多实现的呢?

    在学习的过程中,我发现了如题的这个有趣的问题. 单继承不必解释,一个类只能有一个直接父类:但是对于接口的实现,一个类却能够实现多个接口. 为什么是这种情况呢?我们来举个简单的栗子看一下: class ...

  3. eclipse使用jetty服务器

    1.安装Eclipse Jetty插件: 2.下载jetty(9.4.6): 3.配置jetty运行设置: 右键项目 run configurations,选择jetty webapp,新建项目. c ...

  4. jQuery下锚点的平滑跳转

    对于锚点的平滑跳转,我觉得要谨慎使用,在个人站点或是这个效果含有功能提示可以用一用,在一般的商业性质的网站上,权衡来讲,不用更好,当然,这只是我的个人意见.jQuery库已经为我们做了很多的工作了,所 ...

  5. php错误和异常的重定向

    通过重定向错误或异常,我们可以更安全的显示错误信息,一般也用来记录错误和异常日志. 参数可以是全局函数名,也可以是类中的方法,非静态方法通过数组传递类名和方法名进去, 静态方法直接带命名空间和类名,看 ...

  6. Go-简介-发展

    01-Go语言介绍 目录 Go语言介绍 Go语言特性 Go语言发展(版本/特性) Go语言应用 谁在用 应用领域 Go语言项目 Go语架构 Go语言发展前景 Go语言介绍 Go 即Golang,是Go ...

  7. Cover letter|review|Discussion

    选择期刊考虑影响因子和载文量(流量) 分类:多学科eg:CNS 专业综合:eg:nature子刊:lancet:cell,jacs 细分:eg:CA-A 投完Cover letter后,根据审稿结果修 ...

  8. 解决DIV超出样式长度自动换行

    width: 100px;display:block;word-break: break-all;word-wrap: break-word;

  9. GO、 智能合约、cannot use transactionRecordId + strconv.Itoa(id) (type string) as type byte in append

    1.报错详情 2.在写fabric go智能合约发送的错误,像我这样的新手就是踩坑踩坑踩坑 3.下面是代码片段 4.研究了一下append用法.也看了下GO语言官网文章: var test_str [ ...

  10. oracle 查询表空间

    测试用户连接C:\Users\ZP>sqlplus /nologconn hbcxuser/hbcxpass --查看所有表空间 select * from user_tablespaces-- ...