日志处理

定义日志输出格式

1
2
3
4
5
import logging
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(user)s[%(ip)s] - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
logging.basicConfig(format=LOG_FORMAT, datefmt=DATE_FORMAT)
logging.warning("Some one delete the log file.", exc_info=True, stack_info=True, extra={'user': 'Tom', 'ip':'47.98.53.222'})

日志格式或输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import logging
import logging.handlers
import os    
log = logging.getLogger()
def init_log():
    # 10 * 1024 * 1024 = 10485760
    date = time.strftime("%Y-%m-%d")
    formatter = logging.Formatter("%(asctime)s [%(name)s] %(levelname)s: %(message)s")
    path = os.getcwd()
    if not os.path.exists(os.path.join(path,'log')):
        os.mkdir(os.path.join(path,'log'))
    log_name = date+'.log'
    log_path = os.path.join(path,'log',log_name)
    fh = logging.handlers.RotatingFileHandler(log_path, maxBytes = 10485760, backupCount = 1)
    fh.setFormatter(formatter)
    log.addHandler(fh)
    log.setLevel(logging.INFO)