在编写程序,尤其是某些运行时间长,中间存在可能错误的程序,往往需要记录日志以便于调试.
但是日志的编写往往存在大量重复劳动,并且对于我目前的状况来讲可能需要在已有的程序中添加日志代码.
经过相关资料查阅,我找到了一个内置logging库,其可以较好地实现对于日志的编写.但是查阅了一下相关资料后,发现似乎logging的使用较为复杂,我们往往不需要那么复杂的应用场景,因此我在这里选择另外一个库loguru对日志进行记录
安装
如果使用anaconda,可以用以下命令安装:
1 | conda install -c conda-forge loguru |
简单使用
我们可以直接利用封装好的logger对象,直接对不同级别的日志进行输出,例如使用以下代码可以实现不同级别的日志:
1 | from loguru import logger |
可以注意到在运行时,其对于不同级别的结果,有着不同的格式化与颜色

接下来,我们可以注意到logger编写日志的一个优势在于其无需设定复杂的如处理器,过滤器等信息
输出到文件
我们往往需要将数据输出到文件,尤其是在使用如xspec这样自己会有大量数据输出的程序(默认是在sys.std_err中输出),可以使用add改变输出位置(add的具体用法之后会讲)
1 | logger.add("file_{time}.log") |
其中{time}会自动替换为当前时间,还有其他的格式化字典如下:
| Key | Description | Attributes |
|---|---|---|
| elapsed | The time elapsed since the start of the program | See datetime.timedelta |
| exception | The formatted exception if any, None otherwise |
type, value, traceback |
| extra | The dict of attributes bound by the user (see bind()) |
None |
| file | The file where the logging call was made | name (default), path |
| function | The function from which the logging call was made | None |
| level | The severity used to log the message | name (default), no, icon |
| line | The line number in the source code | None |
| message | The logged message (not yet formatted) | None |
| module | The module where the logging call was made | None |
| name | The __name__ where the logging call was made |
None |
| process | The process in which the logging call was made | name, id (default) |
| thread | The thread in which the logging call was made | name, id (default) |
| time | The aware local time when the logging call was made |
输出到文件还有滚动和压缩等功能,在这里不再过多赘述(目前也用不到)
关于字符着色:
字符着色的问题是通过调节
add中的参数colorize来控制的,其添加后有好处有坏处好处在于可以使用
tail -f等很方便看到数据内容坏处在于由于字符串着色的机理是通过添加字符串进行的,会对编辑器查看带来不便
因此可以尝试同时记录两个log
过滤器与格式化
下面是关于更加复杂的过滤器写法和格式化写法的问题,这里不涉及(可能以后会),可以先看参考资料