简单封装 python 的 logging, 让其更好用

用 python 的 logging 的时候,每次都要写很多话才能记一条 log,于是做了个小模块来让记 log 变得更便捷。

代码如下

log.py

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
import logging, logging.handlers
import config
import inspect

FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOG_LEVEL = logging.DEBUG
logger = {}
handler = logging.handlers.RotatingFileHandler(
config.PATH_LOG_FILE,
maxBytes = 1048576 * 2, # 2MB
backupCount = 5,
)
handler.setFormatter(logging.Formatter(FORMAT))

__all__ = ['Log', 'LogI', 'LogE', 'LogD', 'LogC', 'LogW']
def Log(name):
if inspect.isclass(type(name)): #instance
name = name.__class__.__name__
elif inspect.isclass(type(name)): #class
name = name.__name__
else:
name = name or "no_name"
if name in logger:
return logger[name]
else:
l = logging.getLogger(name)
l.setLevel(LOG_LEVEL)
l.addHandler(handler)
logger[name] = l
return l

def LogI(name, log):
return Log(name).info(log)

def LogE(name, log):
return Log(name).error(log)

def LogD(name, log):
return Log(name).debug(log)

def LogC(name, log):
return Log(name).critical(log)

def LogW(name, log):
return Log(name).warning(log)

试试看:

1
2
3
4
5
6
7
8
9
10
from log import *

class C(object):
def logC(self, log):
LogC(self, log)

instance = C()
LogI(C(), 'passing instance')
LogW(C,'passing class type')
instance.logC("passing self")

来看看我们的 log 输出:

1
2
3
2014-12-06 15:10:56,817 - C - INFO - passing instance
2014-12-06 15:10:56,818 - type - WARNING - passing class type
2014-12-06 15:10:56,818 - C - CRITICAL - passing self

简单封装 python 的 logging, 让其更好用

https://robinxb.com/posts/2014/custom-python-log-module/

作者

薯条

发布于

2014-12-06

更新于

2024-01-15

许可协议

评论