运维工程师的进阶之路

使用logging记录日志(可在其他项目中复用)

2019-05-21  本文已影响0人  Gswu

本部分程序使用logging模块实现。以后在写程序时直接使用即可。希望可以帮助到其他学习python的朋友。

使用方式:

1、在程序目录新建log/,用于存放log

2、程序目录放入已有的log.conf 配置文件。此配置文件配置了三个logging handler,实现了info日志、error日志和terminal输出日志 三种形式。日志存放配置为每天存档一份,存10天日志。

3、在程序目录放入已有的全局日志程序gloLog.py。

4、使用:任何程序中引用并使用:

from groLog import mylog

mylog.errot("this is a error message")
mylog.info("this is a info message")


配置文件:log.conf

[loggers]
keys=root

[handlers]
keys=rotatingFileHandler,streamHandler,errorHandler


[formatters]
keys=simpleFmt

[logger_root]
level=DEBUG
handlers=rotatingFileHandler,streamHandler,errorHandler

[handler_rotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=INFO
formatter=simpleFmt
args=(os.path.abspath(os.getcwd() + "/log/default.log"),"midnight", 1, 10,'utf-8')


[handler_errorHandler]
class=handlers.TimedRotatingFileHandler
level=ERROR
formatter=simpleFmt
args=(os.path.abspath(os.getcwd() + "/log/error.log"), "midnight", 1,30,'utf-8')

[handler_streamHandler]
level=INFO
class=StreamHandler
formatter=simpleFmt
args=(sys.stdout,)

[formatter_simpleFmt]
format=%(asctime)s %(pathname)s(%(lineno)d): [%(levelname)s]%(message)s

gloLog.py

#! /usr/bin/python3
# -*- coding:utf-8 -*-
# @author:gswu
# filename:glo_log.py
# created in 20190520,A special day, thanks to my wife and daughter.

import logging
import logging.config
import os

'''
编写gloLog.py 作为全局log的管理入口。
后续别的模块下的python文件需要使用日志功能时,
需要导入该模块。该模块的原理也很简单,定位到文件路径,
然后通过logger的名字获得要用的logger配置,
'''
def getLogger(name='root'):
    confLog=os.path.abspath(os.getcwd()+"/log.conf")
    logging.config.fileConfig(confLog)
    return logging.getLogger(name)

mylog=getLogger(__name__)

上一篇下一篇

猜你喜欢

热点阅读