python - 两个进程如何使用 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()
如果有人可以帮助我理解这个问题以及我可以采取哪些其他选择来获取新一天文件中的所有日志..
你的建议会很有帮助!!
解决方案
在 Windows 上,正常打开的 (*) 文件只能由一个进程访问。在类 Unix 系统上,多个线程/进程在没有特殊同步的情况下写入同一个文件可能会导致混合输出(不同的说法是不可读的垃圾......)。
这意味着您不能简单地使用FileHandlers
2 个进程来登录到同一个文件。
可以做什么:
- 使用系统日志接口(
SysLogHandler
或NTEventLogHandler
),因为它们希望被许多进程使用。syslog
可以原生使用顺序文件来选择源,并且 NTEventLog 可以导出选定的事件 - 使用继电器。例如,主进程可以使用 a
DatagramHandler
和一个中继进程侦听套接字,读取数据包,将它们格式化回LogRecord
withmakeLogRecord
并最终将它们写入FileHandler
.
(*) 当然,API 允许特殊模式以允许对文件的并发访问,但这不能(容易)从 Python 完成
推荐阅读
- bash - Bash:如何计算一个部分中的行数,增加它并添加另一行
- ios - 如何访问swift 5中tableview单元格内的textview值?
- ktor - 将列添加到具有值的现有表
- python - 如何将 Altair 图表设置为特定的增量?
- angular - 我如何从父级访问 ng-content 组件?
- python - 以较少手动的方式编辑和运行一系列脚本 [Python]
- r - 如何在 case_when 中使用字符串检测?
- python - 如何在没有模块的情况下获得排序数字列表的第一和第三四分位数
- excel - 我无法修复范围内的每个单元格问题。请求帮助
- jquery - 如何正确使用keydown功能?