Open kivdev opened 1 month ago
Hi @kivdev, thanks for investigating the issue and proposing a fix.
The underlying problem, as you understood, is that each worker runs its own instance of the log file handler. Assuming they're all configured to write log to the same file, e.g. if logger.add("file.log")
appears at the root level of the program, then it will inevitably cause conflicts.
Modifying how the file creation-time is read and written is unfortunately not enough. It may make the problem less visible, but there's always a chance that something will go wrong.
Uvicorn workers must be synchronized. They must share the same handler with enqueue=True
.
However, when child workers are started by Uvicorn, they do not inherit the parent handler. Instead, they create a new one that happens to target an already in-use log file.
See this guide about how it should be done correctly: Compatibility with multiprocessing
using enqueue
argument.
Unfortunately, as far as I know, Uvicorn does not provide any API that is compatible with the idiom of "inherited" objects. We can't pass the logger
from the main process to the child ones.
I'm planning to implement some kind of helper (that will use socket
communication between the processes instead of inheritance). However in the meantime, the best thing is to use separate file for separate workers.
I encountered an issue with log rotation when using Uvicorn and Taskiq. I decided to investigate the problem and discovered incorrect logic in the library (in my opinion).
OS: Linux (Debian) Loguru version: >=0.7.2
Problem: Each worker shifts the "user.loguru_crtime" file attribute to its own, which affects previously running workers since their rotation time becomes earlier than that of the last launched worker. As a result, each worker performs its own rotation, which is incorrect behavior.
How I solved the problem:
This solution helped synchronize the workers' log rotation, which resolved the issue.
P.s. I used the "enqueue" and "watch" parameters, but they didn't solve the problem until I made my fix.
Diff: