我需要在我的应用程序中每天生成新的日志,我在应用程序中有两个进程。所以我面临的问题是,一个进程无法写入新的日志,另一个进程正在写入
更多的澄清是我正在做的
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
来登录到同一个文件可以做什么:
SysLogHandler
或NTEventLogHandler
),因为它们预期会被许多进程使用syslog
可以在本机上为选定的源使用顺序文件,而NTEventLog可以导出选定的事件DatagramHandler
和中继进程侦听,读取数据包,用makeLogRecord
将它们格式化回LogRecord
,最后将它们写入FileHandler
李>(*)当然,API允许特殊模式允许并发访问文件,但这不能(轻松地)从Python实现
相关问题 更多 >
编程相关推荐