首页 > 其他分享 >go zap日志库

go zap日志库

时间:2022-11-28 20:45:23浏览次数:45  
标签:... zapcore level interface func go 日志 zap

https://github.com/labring/sealos/blob/main/pkg/utils/logger/logger.go

package logger
   
  import (
  "fmt"
  "os"
  "strings"
  "time"
   
  "go.uber.org/zap"
  "go.uber.org/zap/zapcore"
  "gopkg.in/natefinch/lumberjack.v2"
  )
   
  var (
  defaultLogger *zap.Logger
  )
   
  // init default logger with only console output info above
  func init() {
  zc := zapcore.NewTee(newConsoleCore(zap.InfoLevel))
  defaultLogger = zap.New(zc)
  }
   
  // CfgConsoleLogger config for console logs
  // cfg donot support concurrent calls (as any package should init cfg at startup once)
  func CfgConsoleLogger(debugMode bool, showPath bool) {
  level, zos := genConfigs(debugMode, showPath)
   
  zc := zapcore.NewTee(newConsoleCore(level))
   
  defaultLogger = zap.New(zc, zos...)
  }
   
  // TODO: export more file configs
  // CfgConsoleAndFileLogger config for both console and file logs
  // cfg donot support concurrent calls (as any package should init cfg at startup once)
  func CfgConsoleAndFileLogger(debugMode bool, logDir, name string, showPath bool) {
  level, zos := genConfigs(debugMode, showPath)
   
  filename := fmt.Sprintf("%s/%s.log", logDir, name)
   
  zc := zapcore.NewTee(newConsoleCore(level), newFileCore(filename, level))
   
  defaultLogger = zap.New(zc, zos...)
  }
   
  func genConfigs(debugMode bool, showPath bool) (zapcore.LevelEnabler, []zap.Option) {
  level := zapcore.InfoLevel
  if debugMode {
  level = zapcore.DebugLevel
  }
   
  zos := []zap.Option{
  // zap.AddStacktrace(zapcore.WarnLevel),
  }
  if showPath {
  // skip self wrapper
  zos = append(zos, zap.AddCaller(), zap.AddCallerSkip(2))
  }
   
  return level, zos
  }
   
  func newConsoleCore(le zapcore.LevelEnabler) zapcore.Core {
  consoleLogger := zapcore.Lock(os.Stdout)
   
  zec := zap.NewProductionEncoderConfig()
  zec.EncodeLevel = zapcore.LowercaseColorLevelEncoder
  zec.EncodeTime = zapcore.ISO8601TimeEncoder
  zec.EncodeTime = shortTimeEncoder
  // zec.EncodeTime = zapcore.ISO8601TimeEncoder
  zec.ConsoleSeparator = " "
   
  consoleEncoder := zapcore.NewConsoleEncoder(zec)
   
  return zapcore.NewCore(consoleEncoder, consoleLogger, le)
  }
   
  func newFileCore(filename string, le zapcore.LevelEnabler) zapcore.Core {
  //TODO: export more rotate configs
  fileLogger := zapcore.AddSync(&lumberjack.Logger{
  Filename: filename,
  MaxSize: 10, // megabytes per file
  })
   
  zec := zap.NewProductionEncoderConfig()
  zec.EncodeTime = zapcore.ISO8601TimeEncoder
   
  fileEncoder := zapcore.NewJSONEncoder(zec)
  return zapcore.NewCore(fileEncoder, fileLogger, le)
  }
   
  const shortTimeLayout = "2006-01-02T15:04:05"
   
  func shortTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
  enc.AppendString(t.Format(shortTimeLayout))
  }
   
  // IsDebugMode check DebugLevel enabled
  func IsDebugMode() bool {
  return defaultLogger.Core().Enabled(zapcore.DebugLevel)
  }
   
  // Fatal logs a message at emergency level and exit.
  func Fatal(f interface{}, v ...interface{}) {
  defaultLogger.Sugar().Fatalf(formatLog(zapcore.FatalLevel, f, v...))
  }
   
  // Panic logs a message at emergency level and exit.
  func Panic(f interface{}, v ...interface{}) {
  defaultLogger.Sugar().Panicf(formatLog(zapcore.PanicLevel, f, v...))
  }
   
  // Error logs a message at error level.
  func Error(f interface{}, v ...interface{}) {
  defaultLogger.Sugar().Errorf(formatLog(zapcore.ErrorLevel, f, v...))
  }
   
  // Warn logs a message at warning level.
  func Warn(f interface{}, v ...interface{}) {
  defaultLogger.Sugar().Warnf(formatLog(zapcore.WarnLevel, f, v...))
  }
   
  // Info logs a message at info level.
  func Info(f interface{}, v ...interface{}) {
  defaultLogger.Sugar().Infof(formatLog(zapcore.InfoLevel, f, v...))
  }
   
  // Debug logs a message at debug level.
  func Debug(f interface{}, v ...interface{}) {
  defaultLogger.Sugar().Debugf(formatLog(zapcore.DebugLevel, f, v...))
  }
   
  func formatLog(l zapcore.Level, f interface{}, v ...interface{}) string {
  var msg string
  switch f := f.(type) {
  case string:
  msg = f
  if len(v) == 0 {
  return appendColor(l, msg)
  }
  if strings.Contains(msg, "%") && !strings.Contains(msg, "%%") {
  //format string
  } else {
  //do not contain format char
  msg += strings.Repeat(" %v", len(v))
  }
  default:
  msg = fmt.Sprint(f)
  if len(v) == 0 {
  return appendColor(l, msg)
  }
  msg += strings.Repeat(" %v", len(v))
  }
  return appendColor(l, fmt.Sprintf(msg, v...))
  }
   
  func appendColor(l zapcore.Level, s string) string {
  // default all red
  c := uint8(31)
  switch l {
  case zapcore.DebugLevel:
  c = uint8(35) // Magenta
  case zapcore.InfoLevel:
  c = uint8(34) // Blue
  case zapcore.WarnLevel:
  c = uint8(33) // Yellow
  }
  return fmt.Sprintf("\x1b[%dm%s\x1b[0m", c, s)
  }

Footer

   

标签:...,zapcore,level,interface,func,go,日志,zap
From: https://www.cnblogs.com/cheyunhua/p/16933545.html

相关文章

  • go源码学习(一):数据结构-数组
    数组是相同类型元素的集合,在内存中对应一块连续的内存空间。数组类型是通过存储的元素类型以及能够存储的大小两个维度来决定的,一旦声明之后大小就不可更改。初始化go语......
  • Android Google开源库——Volley的简单使用
    介绍一下AndroidGoogle开源库——Volley的简单使用volley 项目地址 ​​https://github.com/smanikandan14/Volley-demo​​JSON,图像等的异步下载;网络请求的排序(sc......
  • MYSQL之日志管理、备份与恢复
    一.MySQL日志管理MySQL的日志默认保存位置为/usr/local/mysql/dataMySQL的日志配置文件为/etc/my.cnf ,里面有个[mysqld]项修改配置文件:vim/etc/my.cnf[mysqld]1......
  • MySQL日志管理、备份与恢复
    一.MySQL日志管理MySQL的日志默认保存位置为/usr/local/mysql/dataMySQL的日志配置文件为/etc/my.cnf ,里面有个[mysqld]项修改配置文件:vim/etc/my.cnf[mysqld]1......
  • zabbix监控进程和监控日志
    zabbix监控进程和监控日志文章目录zabbix监控进程和监控日志一、自定义监控进程1、新建脚本存放目录2、修改zabbix_agentd.conf文件3、zabbixserver端进行测试......
  • 日志式文件系统(ext3)详解
    一、概述通常在系统运行中写入文件内容的同时,并没有写入文件的元数据(如权限、所有者及创建和访问时间),如果在写入文件内容之后与写入文件元数据之前的时间差里,系统非正......
  • jQuery插件FullCalendar日程表实现可扩展Google日历功能
    这个介绍jQuery日历FullCalendar插件是一个非常不错的日历工具,可用于制作日程表或计划安排等,可扩展Google日历功能,制作个性化的日程表,同时可绑定点击事件或拖动事件,使用非常......
  • Django视图中的请求与响应
    一请求一限制http请求视图中的request,实际上是django源码中的HTTPRequest的子类WSGIRequest类的实例对象,主要由django对客户端请求的http协议报文进行解析后得到的请求......
  • Pycharm 搭建 Django 项目
    1.安装需求在使用python框架Django需要注意下面事项Pycharm版本是专业版而不是社区版本Pycharm配置好了python解释器(一般我们现在用的都是python3)我自己使......
  • 6.go中的派生/复杂数据类型
    1.指针1.基本数据类型也叫值类型,在内存中存储值,指针类型一个地址,地址指向的空间存储的值才是        2.&,获取地址2.数组3.结构体......