python logging string formatting

前端 未结 3 2110
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 14:09

I am using python\'s log formatter to format log records and i have a fmt value of

fmt = \"[%(filename)s:%(lineno)s] %(message)s\"

What i w

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 14:42

    Using @rob-cowie's answer as a basis, I've found the following useful:

    class MyFormatter(logging.Formatter):
        width = 24
        datefmt='%Y-%m-%d %H:%M:%S'
    
        def format(self, record):
            cpath = '%s:%s:%s' % (record.module, record.funcName, record.lineno)
            cpath = cpath[-self.width:].ljust(self.width)
            record.message = record.getMessage()
            s = "%-7s %s %s : %s" % (record.levelname, self.formatTime(record, self.datefmt), cpath, record.getMessage())
            if record.exc_info:
                # Cache the traceback text to avoid converting it multiple times
                # (it's constant anyway)
                if not record.exc_text:
                    record.exc_text = self.formatException(record.exc_info)
            if record.exc_text:
                if s[-1:] != "\n":
                    s = s + "\n"
                s = s + record.exc_text
            #if record.stack_info:
            #    if s[-1:] != "\n":
            #        s = s + "\n"
            #    s = s + self.formatStack(record.stack_info)
            return s
    
    logFormatter = MyFormatter()
    logger = logging.getLogger("example")
    logger.setFormatter(logFormatter)
    

    Which gives output like:

    WARNING 2014-03-28 16:05:09 module:function:31       : Message
    WARNING 2014-03-28 16:05:09 dule:longerfunctions:140 : Message
    

提交回复
热议问题