使用格式化和 logrotate 进行日志设置

问题描述

在下面的程序中,我尝试使用 basicConfig 以我需要的格式设置日志,并使用 RotatingFileHandler 轮换日志。

但得到错误

Traceback (most recent call last):  
  File "C:\Python27\lib\logging\handlers.py",line 77,in emit  
    self.doRollover()  
  File "C:\Python27\lib\logging\handlers.py",line 142,in doRollover  
    os.rename(self.baseFilename,dfn)  
WindowsError: [Error 32] The process cannot access the file because it is being used by another process  
Logged from file log_rotate.py,line 53  

无法弄清楚问题出在哪里,python 新手。 有人可以指出我正确的方向。

import os
import logging
import time
import string
from ctypes import windll
from logging.handlers import RotatingFileHandler

LOG_FILE = 'C:\\temp\\debug.log'

def get_drives():
    drives = []
    bitmask = windll.kernel32.GetLogicalDrives()
    for letter in string.ascii_uppercase:
        if bitmask & 1:
            drives.append(letter)
        bitmask >>= 1

    return drives

def create_temp_dir():

    drives = []
    drives = get_drives()
    temp_dir = drives[0]+':\\temp\\'
    if not os.path.exists(temp_dir):
        print ( " creating temp for logs and etc ",temp_dir )
        os.makedirs(temp_dir)
    return temp_dir

def make_log_setup():
    global LOG_FILE
    temp_dir = create_temp_dir()
    log_file = temp_dir+'debug.log'
    date_strftime_format = "%d-%b-%y %H:%M:%s"
    message_format='%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s'
    logging.basicConfig(filename = log_file,format = message_format,datefmt = date_strftime_format,level=logging.DEBUG)

def create_rotating_log(path):
    """
    Creates a rotating log
    """
    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.DEBUG)
    
    # add a rotating handler
    handler = RotatingFileHandler(path,maxBytes=20,backupCount=5)
    logger.addHandler(handler)
    
    for i in range(6):
        logger.info("This is test log line %s" % i)
        time.sleep(1.5)
        

if __name__ == "__main__":
    #log_file = "test.log"
    make_log_setup()
    create_rotating_log(LOG_FILE)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...