英文:
python loguru output to stderr and a file
问题
我有以下配置我的日志记录器实例的代码行
```python
logger.add(sys.stderr, level=log_level, format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS zz}</green> | <level>{level: <8}</level> | <yellow>Line {line: >4} ({file}):</yellow> <b>{message}</b>", colorize=True, backtrace=True, diagnose=True)
我想配置我的日志记录器,使用上面的配置,并将日志输出到文件,这样当我调用logger.whatever()时,它会在终端和日志文件中输出
这样,如果我在进行开发工作并直接运行文件时,我可以在终端中看到输出,而当代码由cronjob在服务器上运行时,它可以记录到文件中
我不太理解“sinks”的整个概念,所以如果这是一个简单的问题,我很抱歉
<details>
<summary>英文:</summary>
I have the following line that configures my logger instance
logger.add(sys.stderr, level=log_level, format="<green>{time:YYYY-MM-DD HH:mm:ss.SSS zz}</green> | <level>{level: <8}</level> | <yellow>Line {line: >4} ({file}):</yellow> <b>{message}</b>", colorize=True, backtrace=True, diagnose=True)
I want to configure my logger to use the above, and also output to a file, so that when I call logger.whatever() it outputs to the terminal and to a log file
This way, if I'm doing dev work and running the file directly, I can see the output in my terminal, and when the code is being run on a server by a cronjob, it can log to a file
I don't understand the whole concept of the "sinks" so sorry if this is an easy question
</details>
# 答案1
**得分**: 2
在日志记录的上下文中,“sink”指的是日志记录的输出目标。它可以是流(如`sys.stderr`或`sys.stdout`)、文件路径或接受日志消息作为输入的任何自定义函数。详见[文档](https://loguru.readthedocs.io/en/stable/api/logger.html#sink)以了解更多详情。
使用Loguru,你可以添加尽可能多的sinks。这意味着在你的情况下,你可以有两个sinks:一个写入到`sys.stderr`,另一个写入到`file.log`。
每当使用`logger.info()`记录消息时,比如,它将被发送到已添加的每个sink,并根据相应的配置进行处理。
<details>
<summary>英文:</summary>
In the context of logging, a "sink" refers to an output destination for log records. It can be a stream (such as `sys.stderr` or `sys.stdout`), a file path, or any custom function that accepts the logged message an input. See [documentation](https://loguru.readthedocs.io/en/stable/api/logger.html#sink) for more details.
Using Loguru, you can add as many sinks as you like. This means that in your case, you can have two sinks: one writing to `sys.stderr` and another one writing to `file.log`.
```python
log_level = "DEBUG"
log_format = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS zz}</green> | <level>{level: <8}</level> | <yellow>Line {line: >4} ({file}):</yellow> <b>{message}</b>"
logger.add(sys.stderr, level=log_level, format=log_format, colorize=True, backtrace=True, diagnose=True)
logger.add("file.log", level=log_level, format=log_format, colorize=False, backtrace=True, diagnose=True)
Each time a message is logged with logger.info()
for example, it will be sent to each of the added sinks and processed based on the the corresponding configuration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论