-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
52 lines (44 loc) · 1.92 KB
/
utils.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
47
48
49
50
# -*- coding:utf-8 -*-
import os
import re
import logging
import datetime as dt
from logging.handlers import RotatingFileHandler
from logging.handlers import TimedRotatingFileHandler
class SubFormatter(logging.Formatter):
converter=dt.datetime.fromtimestamp
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
s = ct.strftime(datefmt)
else:
t = ct.strftime("%Y-%m-%d %H:%M:%S")
s = "%s,%03d" % (t, record.msecs)
return s
class Logging(object):
def __init__(self, log_dir='./logs', log_name='server', console=True):
self.logger = logging.getLogger(log_name)
self.logger.setLevel(logging.DEBUG)
#formatter = logging.Formatter("%(asctime)s [%(name)s] [%(funcName)s:%(lineno)s] [%(levelname)s]: %(message)s", "%Y-%m-%d %H:%M:%S")
formatter = SubFormatter(fmt='%(asctime)s [%(name)s] [%(funcName)s:%(lineno)s] [%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S.%f')
# file handler
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = log_dir + '/' + log_name
#fh = logging.FileHandler(log_file)
#fh = TimedRotatingFileHandler(filename=log_file, when="D", interval=1, backupCount=7)
fh = TimedRotatingFileHandler(filename=log_file, when="H", interval=1, backupCount=3*24)
fh.suffix = "%Y-%m-%d_%H-%M.log"
fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
self.logger.addHandler(fh)
# console handler
# define a Handler which writes INFO messages or higher to the sys.stderr
if console:
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
self.logger.addHandler(ch)
def getLogger(self):
return self.logger