logger_config.ini
[loggers]
keys = root
[logger_root]
level = DEBUG
handlers = consoleHandler, fileHandler
[handlers]
keys = consoleHandler, fileHandler
[handler_consoleHandler]
class = StreamHandler
level = INFO
formatter = simpleFormatter
args = (sys.stdout,)
[handler_fileHandler]
class = FileHandler
level = DEBUG
formatter = simpleFormatter
args = ('/var/log/a.log', 'a')
[formatters]
keys = simpleFormatter
[formatter_simpleFormatter]
format = %(asctime)s - %(filename)s - %(levelname)s - %(message)s
datefmt = %Y-%m-%d %H:%M:%S
logger.py
#!/usr/bin/env python
# -*- coding: utf-8 -*
#author: qinqin.fan
"""use to record log"""
#---------------------
#2017-1-11 created
#2019-7-3 modified
"""changed for dynamic log name"""
import logging
from logging.config import logging
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))))
class Logger(object):
"""add handler"""
def __init__(self, file_name):
logging.config.fileConfig("/mnt/user/qinqin/scripts/xtao-test-glusterfs/conf/logger/logger_config.ini")
self.logger = logging.getLogger(__name__)
self.file_name_abs = '/var/log/' + file_name + ".log"
def logger(self):
root_logger = logging.getLogger('root')
handler = logging.FileHandler(self.file_name_abs)
#fmt = logging.Formatter('%(asctime)s|%(message)s')
#handler.setFormatter(fmt)
root_logger.addHandler(handler)
#root_logger.setLevel(logging.DEBUG)
return root_logger
参考:
http://www.php.cn/python-tutorials-351909.html
https://docs.python.org/3/howto/logging.html
https://docs.python.org/2/library/logging.html