首页 > 解决方案 > 两个进程如何使用 Python 登录单个文件?/ 从多个进程记录到单个文件

问题描述

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

为了更清楚,这里是我在做什么..

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()

如果有人可以帮助我理解这个问题以及我可以采取哪些其他选择来获取新一天文件中的所有日志..

你的建议会很有帮助!!

标签: pythonloggingprocesserror-logging

解决方案


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

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

可以做什么:

  1. 使用系统日志接口(SysLogHandlerNTEventLogHandler),因为它们希望被许多进程使用。syslog可以原生使用顺序文件来选择源,并且 NTEventLog 可以导出选定的事件
  2. 使用继电器。例如,主进程可以使用 aDatagramHandler和一个中继进程侦听套接字,读取数据包,将它们格式化回LogRecordwithmakeLogRecord并最终将它们写入FileHandler.

(*) 当然,API 允许特殊模式以允许对文件的并发访问,但这不能(容易)从 Python 完成


推荐阅读