两个进程如何使用Python登录单个文件?/从多个进程记录到单个文件

2024-10-01 07:10:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在我的应用程序中每天生成新的日志,我在应用程序中有两个进程。所以我面临的问题是,一个进程无法写入新的日志,另一个进程正在写入

更多的澄清是我正在做的

import logging
import os, sys
import os.path
import datetime
from threading import Thread
import time

firstTime = "false"


def initialize_logger(fileName):

    global firstTime
    try:
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        output_dir = os.getcwd()
        if firstTime == "true":
            for handler in logger.handlers[:]:  # get rid of existing old handlers                
                logger.removeHandler(handler)
        # create debug file handler and set level to debug
        try:
            handler = logging.FileHandler(os.path.join(output_dir, fileName), "w")
        except:
            print("problem to create log")

        handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter("[%(levelname)s] (%(threadName)-30s) %(asctime)s %(message)s ")
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        firstTime = "true"
    except Exception as ex:
        exc_type, exc_obj, tb = sys.exc_info()
        template = "An exception of type {0} occurred at {1}. Arguments:\n{2!r}"
        message = template.format(type(ex).__name__, tb.tb_lineno, ex.args)
        logging.error(message)


def daily_log(dummyStr):
    global firstTime

    try:
        now = datetime.datetime.now()        
        log_day = now.day
        initialize_logger("Log_start.log")
        while True:
            currentDate = datetime.datetime.now().day
            time.sleep(60)

            if currentDate != log_day:  # New day started              
                initialize_logger("Log_continue.log")

    except Exception as ex:
        exc_type, exc_obj, tb = sys.exc_info()
        template = "An exception of type {0} occurred at {1}. Arguments:\n{2!r}"
        message = template.format(type(ex).__name__, tb.tb_lineno, ex.args)
        logging.error(message)


logThread = Thread(target=daily_log, name="dailyLogThread", args=("dummy",))

logThread.start()

如果有人能帮助我理解这个问题,以及我可以采取什么其他替代方法来获取新日文件中的所有日志

你的建议会很有帮助的


Tags: importlogmessagedatetimeosloggingtypetemplate
1条回答
网友
1楼 · 发布于 2024-10-01 07:10:57

在Windows上,正常打开的(*)文件只能由一个进程访问。在类Unix系统上,如果在没有特殊同步的情况下将多个线程/进程写入同一个文件,可能会导致混合输出(以不同的方式称为不可读垃圾…)

这意味着您不能简单地对两个进程使用FileHandlers来登录到同一个文件

可以做什么:

  1. 使用系统日志接口(SysLogHandlerNTEventLogHandler),因为它们预期会被许多进程使用syslog可以在本机上为选定的源使用顺序文件,而NTEventLog可以导出选定的事件
  2. 使用继电器。例如,主进程可以在套接字上使用DatagramHandler和中继进程侦听,读取数据包,用makeLogRecord将它们格式化回LogRecord,最后将它们写入FileHandler

(*)当然,API允许特殊模式允许并发访问文件,但这不能(轻松地)从Python实现

相关问题 更多 >