当前位置:网站首页>golang日志库zerolog使用记录
golang日志库zerolog使用记录
2022-07-30 18:58:00 【geekqian】
效果



安装
github官方地址:https://github.com/rs/zerolog
go get -u github.com/rs/zerolog/log
配置
分享下自己用的,有特殊需求的自己看下官方文档,更全面。
需求是: 把日志同时往控制台和日志文件里输出,日志文件用日期每日分拆。
建了log包单独封装。log.go
package log
import (
"fmt"
"github.com/rs/zerolog"
"os"
"strings"
"time"
)
var Logger zerolog.Logger
func init() {
timeFormat := "2006-01-02 15:04:05"
zerolog.TimeFieldFormat = timeFormat
// 创建log目录
logDir := "./run_log/"
err := os.MkdirAll(logDir, os.ModePerm)
if err != nil {
fmt.Println("Mkdir failed, err:", err)
return
}
fileName := logDir + time.Now().Format("2006-01-02") + ".log"
logFile, _ := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
consoleWriter := zerolog.ConsoleWriter{
Out: os.Stdout, TimeFormat: timeFormat}
consoleWriter.FormatLevel = func(i interface{
}) string {
return strings.ToUpper(fmt.Sprintf("| %-6s|", i))
}
consoleWriter.FormatMessage = func(i interface{
}) string {
return fmt.Sprintf("%s", i)
}
consoleWriter.FormatFieldName = func(i interface{
}) string {
return fmt.Sprintf("%s:", i)
}
consoleWriter.FormatFieldValue = func(i interface{
}) string {
return fmt.Sprintf("%s;", i)
}
multi := zerolog.MultiLevelWriter(consoleWriter, logFile)
Logger = zerolog.New(multi).With().Timestamp().Logger()
}
使用
使用时引入自己项目下的log包并且用包里的 Logger 输出。
import "myproject/log"
func SignIn(){
log.Logger.Info().
Str("website", "xx").
Str("account", account).
Msg("开始登录...")
}
边栏推荐
- 微信小程序云开发 | 城市信息管理
- Chapter 4 Controlling the Execution Flow
- - daily a LeetCode 】 【 191. A number of 1
- requet.getHeader("token") is null
- Swiper rotates pictures and plays background music
- LeetCode 练习——关于查找数组元素之和的两道题
- 沉浸式体验科大讯飞2022消博会“官方指定产品”
- 常见链表题及其 Go 实现
- What kind of framework is friendly to developers?
- MYSQL (Basic) - An article takes you into the wonderful world of MYSQL
猜你喜欢

Scrapy framework is introduced

一文读懂“语言模型”

MySQL data types

Swiper轮播图片并播放背景音乐

OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.解决方法

攻防世界web-Cat

卫星电话是直接与卫星通信还是通过地面站?

6块钱1斤,日本公司为何来中国收烟头?

防抖和节流有什么区别,分别用于什么场景?

使用postman调接口报Content type ‘text/plain;charset=UTF-8‘ not supported
随机推荐
7.30模拟赛总结
设计消息队列存储消息数据的 MySQL 表格
【每日一道LeetCode】——191. 位1的个数
Go system collection
沉浸式体验科大讯飞2022消博会“官方指定产品”
Delay queue optimization (2)
第14章 类型信息
- daily a LeetCode 】 【 191. A number of 1
Deepen school-enterprise cooperation and build an "overpass" for the growth of technical and skilled talents
Scala学习:breakable
Does the satellite phone communicate directly with the satellite or through a ground station?
【PHPWord】Quick Start of PHPWord in PHPOffice Suite
DM8: Single database and single instance to build a local data guard service
Chapter 14 Type Information
深化校企合作 搭建技术技能人才成长“立交桥”
Node encapsulates a console progress bar plugin
MySQL数据类型
Anaconda Navigator卡在loading applications
JS提升:Promise中reject与then之间的关系
深入浅出边缘云 | 3. 资源配置