问题:
假设我们自己写了一个名为 log_config.py 的日志记录程序模块。此模块会被其他程序所引用,如下例子。
import log_config
logger = log_config.log_config("./test_log.txt", "tester")
logger.info("log start.")
logger.info("something happens")
logger.info("log end.")
解决方法:
- 先看一下目前系统中的Python 路径情况:
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
- 结果显示,在这几个目录都是 Python 的系统目录。我们的模块可以放在如下二个目录即可。
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages'
更进一步:
- 如果自定义的模块不想与Python 系统的模块放在同一目录下,可以在上面二个目录中增加一个路径文件 user_defined_modules.pth 。此文件内容就是我们自定义模块的存放路径。例子如下:
/home/tom/python_modules/
在 /home/tom/python_module/ 目录中把我们的模块文件 log_config.py 存放好即可。
附录 log_config.py 源码:
此代码可以设置日志文件的生成规则,目录设置的是 1 小时 1 个文件。如果一小时内单个文件大小超过 10 MB会自动分割成多个文件。
#!/usr/bin/python
# encoding=utf-8
#example
#import log_config
#logger = log_config.log_config("./test_log.txt", "tester")
#logger.info("log start")
#logger.info("log end")
#!/usr/bin/env python
# -*- coding:utf-8 -*
""" Setup a Logger which creates a new log file when it
reach up to it limits, such as one hour and file size 10 MB.
"""
__author__ = "Zhiwei Yan"
__copyright__ = "Copyright 2016, The Common tools Project"
__credits__ = ["Zhiwei Yan"]
__license__ = "Apache License"
__version__ = "2.0"
__maintainer__ = "Zhiwei YAN"
__email__ = "jerod.yan@gmail.com"
__status__ = "Production"
import logging
import logging.handlers as handlers
import time, datetime
class SizedTimedRotatingFileHandler(handlers.TimedRotatingFileHandler):
"""
Handler for logging to a set of files, which switches from one file
to the next when the current file reaches a certain size, or at certain
timed intervals
"""
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None,
delay=0, when='h', interval=1, utc=False):
# If rotation/rollover is wanted, it doesn't make sense to use another
# mode. If for example 'w' were specified, then if there were multiple
# runs of the calling application, the logs from previous runs would be
# lost if the 'w' is respected, because the log file would be truncated
# on each run.
if maxBytes > 0:
mode = 'a'
handlers.TimedRotatingFileHandler.__init__(
self, filename, when, interval, backupCount, encoding, delay, utc)
self.maxBytes = maxBytes
def shouldRollover(self, record):
"""
Determine if rollover should occur.
Basically, see if the supplied record would cause the file to exceed
the size limit we have.
"""
if self.stream is None: # delay was set...
self.stream = self._open()
if self.maxBytes > 0: # are we rolling over?
msg = "%s\n" % self.format(record)
self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
if self.stream.tell() + len(msg) >= self.maxBytes:
return 1
t = int(time.time())
if t >= self.rolloverAt:
return 1
return 0
def log_config(log_filename, logger_str):
logging.basicConfig(format = "%(asctime)s" "[%(module)s:%(funcName)s:%(lineno)d]\n" "%(message)s \n")
logger=logging.getLogger(logger_str)
logger.propagate = False
logger.setLevel(logging.DEBUG)
handler=SizedTimedRotatingFileHandler(
log_filename,
maxBytes=10*1024*1024, backupCount=24*30,
when='h',interval=1,
# encoding='bz2', # uncomment for bz2 compression
)
logformatter = logging.Formatter("%(asctime)s" "[%(module)s:%(funcName)s:%(lineno)d]\n" "%(message)s \n")
handler.setFormatter(logformatter)
logger.addHandler(handler)
return logger