Go的日志库go-logging
配置文件config.yaml
log:
prefix: '[MY-LOG] '
log-file: true
stdout: 'DEBUG'
file: 'DEBUG'
config/config.go
package config
type Log struct {
Prefix string `mapstructure:"prefix" json:"prefix"`
LogFile bool `mapstructure:"log-file" json:"logFile"`
Stdout string `mapstructure:"stdout" json:"stdout"`
File string `mapstructure:"file" json:"file"`
}
type Config struct {
Log Log `json:"log"`
}
global/global.go
package global import (
oplogging "github.com/op/go-logging"
"github.com/spf13/viper"
"go_Logger/config"
) var (
CONFIG config.Config
VP *viper.Viper
LOG *oplogging.Logger
)
读取配置文件
//const defaultConfigFile = "config/config.json"
const defaultConfigFile = "config/config.yaml" func init() {
v := viper.New()
v.SetConfigFile(defaultConfigFile)
err := v.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
v.WatchConfig() v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
if err := v.Unmarshal(&global.CONFIG); err != nil {
fmt.Println(err)
}
})
if err := v.Unmarshal(&global.CONFIG); err != nil {
fmt.Println(err)
}
global.VP = v
}
initizlize/go-logging.go
package initizlize import (
"fmt"
rotatelogs "github.com/lestrrat/go-file-rotatelogs"
oplogging "github.com/op/go-logging"
"go_Logger/config"
"go_Logger/global"
"go_Logger/utils"
"io"
"os"
"strings"
"time"
) const (
logDir = "log"
logSoftLink = "latest_log"
module = "go_Logger"
) var (
defaultFormatter = `%{color}%{time:2006/01/02 - 15:04:05.000} %{longfile} %{color:bold} [%{level:.6s}] %{message}%{color:reset}`
) func InitGlobalLog() {
c := global.CONFIG.Log
if c.Prefix == "" {
_ = fmt.Errorf("logger prefix not found")
}
logger := oplogging.MustGetLogger(module)
var backends []oplogging.Backend
backends = registerStdout(c, backends)
backends = registerFile(c, backends) oplogging.SetBackend(backends...)
global.LOG = logger
} func registerStdout(c config.Log, backends []oplogging.Backend) []oplogging.Backend {
if c.Stdout != "" {
level, err := oplogging.LogLevel(c.Stdout)
if err != nil {
fmt.Println(err)
}
backends = append(backends, createBackend(os.Stdout, c, level))
} return backends
} func registerFile(c config.Log, backends []oplogging.Backend) []oplogging.Backend {
if c.File != "" {
if ok, _ := utils.PathExists(logDir); !ok {
// directory not exist
fmt.Println("create log directory")
_ = os.Mkdir(logDir, os.ModePerm)
}
fileWriter, err := rotatelogs.New(
logDir+string(os.PathSeparator)+"%Y-%m-%d-%H-%M.log",
// generate soft link, point to latest log file
//rotatelogs.WithLinkName(logSoftLink),
// maximum time to save log files
rotatelogs.WithMaxAge(7*24*time.Hour),
// time period of log file switching
rotatelogs.WithRotationTime(24*time.Hour),
)
if err != nil {
fmt.Println(err)
return backends
}
level, err := oplogging.LogLevel(c.File)
if err != nil {
fmt.Println(err)
}
backends = append(backends, createBackend(fileWriter, c, level))
} return backends
} func createBackend(w io.Writer, c config.Log, level oplogging.Level) oplogging.Backend {
backend := oplogging.NewLogBackend(w, c.Prefix, 0)
stdoutWriter := false
if w == os.Stdout {
stdoutWriter = true
}
format := getLogFormatter(c, stdoutWriter)
backendLeveled := oplogging.AddModuleLevel(oplogging.NewBackendFormatter(backend, format))
backendLeveled.SetLevel(level, module)
return backendLeveled
} func getLogFormatter(c config.Log, stdoutWriter bool) oplogging.Formatter {
pattern := defaultFormatter
if !stdoutWriter {
// Color is only required for console output
// Other writers don't need %{color} tag
pattern = strings.Replace(pattern, "%{color:bold}", "", -1)
pattern = strings.Replace(pattern, "%{color:reset}", "", -1)
}
if !c.LogFile {
// Remove %{logfile} tag
pattern = strings.Replace(pattern, "%{longfile}", "", -1)
}
return oplogging.MustStringFormatter(pattern)
}
main.go
package main import (
"go_Logger/global"
initizlize "go_Logger/initialize"
) func main() {
initizlize.InitGlobalLog()
global.LOG.Debug("go-logging日志打印测试")
global.LOG.Warning("go-logging日志打印测试")
global.LOG.Error("go-logging日志打印测试")
}
Go的日志库go-logging的更多相关文章
- python找寻合适的日志库logging Handler——Handler自定义实现
最近在用python tornado开发一个app的服务端.投产的系统肯定需要包含日志功能,这里就自然想到了用python自带的logging库. logging中日志内容的输出都交由Handle ...
- python logging日志库
项目中使用的日志库是使用python官方库logging封装的,但是居然一直么有设置日志自动滚动,经常会受到告警说哪台机器磁盘空间又满,清理一下,于是研究一下,解决这个问题. 参考:https://d ...
- Python之日志处理(logging模块)
本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging四大组件记录日志 配置logging的几种方式 向日 ...
- 以打印日志为荣之logging模块详细使用
啄木鸟社区里的Pythonic八荣八耻有一条: 以打印日志为荣 , 以单步跟踪为耻; 很多程序都有记录日志的需求,并且日志中包含的信息既有正常的程序访问日志,还可能有错误.警告等信息输出,python ...
- glog日志库使用笔记
日志能方便地诊断程序原因.统计程序运行数据,是大型软件系统必不可少的组件之一.glog 是google的开源日志系统,相比较log4系列的日志系统,它更加轻巧灵活. 在Github上下载glog,解压 ...
- 【转】Python之日志处理(logging模块)
[转]Python之日志处理(logging模块) 本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging ...
- C/C++log日志库比较
事实上,在C的世界里面没有特别好的日志函数库(就像Java里面的的log4j,或者C++的log4cxx).C程序员都喜欢用自己的轮子.printf就是个挺好的轮子,但没办法通过配置改变日志的格式或者 ...
- C++的开源跨平台日志库glog学习研究(三)--杂项
在前面对glog分别做了两次学习,请看C++的开源跨平台日志库glog学习研究(一).C++的开源跨平台日志库glog学习研究(二)--宏的使用,这篇再做个扫尾工作,算是基本完成了. 编译期断言 动态 ...
- C++的开源跨平台日志库glog学习研究(二)--宏的使用
上一篇从整个工程上简单分析了glog,请看C++的开源跨平台日志库glog学习研究(一),这一篇对glog的实现代码入手,比如在其源码中以宏的使用最为广泛,接下来就先对各种宏的使用做一简单分析. 1. ...
- C++的开源跨平台日志库glog学习研究(一)
作为C++领域中为数不多的好用.高效的.跨平台的日志工具,Google的开源日志库glog也算是凤毛麟角了.glog 是一个C++实现的应用级日志记录框架,提供了C++风格的流操作. 恰巧趁着五一我也 ...
随机推荐
- Python的安装和卸载
一.Python的安装,去Python官网https://www.python.org/downloads/下载对应安装包 进入官网后鼠标移动到downloads处然后点击Windows 二.安装包下 ...
- react的diff算法与antd中switch组件不更新问题
问题描述: 现在有个需求,现有一个列表table,里面的数据有启用的也有关闭的,switch组件会根据数据状态展示,同时进行排序,启用数据在前面,未启用的在后面.如图 然后现在需要操作,假如我将第四条 ...
- Apache Log4j2,RASP 防御优势及原理
Apache Log4j2 远程代码执行漏洞已爆发一周,安全厂商提供各类防御方案和检测工具,甲方团队连夜应急. 影响持续至今,网上流传的各种利用和绕过姿势还在层出不穷,影响面持续扩大.所有安全人都开始 ...
- others_babystack
一道泄露canary+rop常规的题. 这道题让我学习到了,原来canary的最后一位是\x00,又因为是小端存储,所以在内存中我位置是在开头的. 来,下载文件检查一下保护. 开启了canary和nx ...
- YonBuilder低代码开发实践:4行代码实现跨实体列表数据同步
提到增.删.改.查等数据维护,后端开发者们再熟悉不过了.传统的数据维护通过操作数据库的方式实现,步骤比较繁琐,需要通过Java代码实现数据库链接,然后编写SQL语句.编写实体,将想要的数据存到相应的数 ...
- 其他(Excel函数集团)
此处文章均为本妖原创,供下载.学习.探讨! 文章下载源是Office365国内版1Driver,如有链接问题请联系我. 请勿用于商业!谢谢 下载地址:https://officecommunity-m ...
- OpenWrt之DNS设置
目录 OpenWrt之DNS设置 0.前言 1.WAN口 2.Lan口 3.LAN口DHCP选项 4.DHCP/DNS 5.总结 参考(Thanks) 附录.DHCP OPTION OpenWrt之D ...
- Elasticsearch删除所有数据
使用post请求 POST http://localhost:9200/索引/标签/_delete_by_query?pretty { "query": { "match ...
- JAVA比较指定的两个日期
判断指定日期是否在某个日期内 public static SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); p ...
- 【LeetCode】346. Moving Average from Data Stream 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 队列 日期 题目地址:https://leetcode ...