# 记录中

> 原文： [https://pythonspot.com/logging/](https://pythonspot.com/logging/)

## Python 日志记录

We can track events in a software application, this is known as **logging**. Let’s start with a simple example, we will log a warning message.

与仅打印错误相反，可以将日志记录配置为禁用输出或保存到文件。 这是简单打印错误的一大优势。

## 记录示例

```py
import logging

# print a log message to the console.
logging.warning('This is a warning!')

```

这将输出：

```py
WARNING:root:This is a warning!

```

我们可以轻松地输出到文件：

```py
import logging

logging.basicConfig(filename='program.log',level=logging.DEBUG)
logging.warning('An example message.')
logging.warning('Another message')

```

日志消息的重要性取决于严重性。

## 严重程度

The logger module has several levels of severity. We set the level of severity using this line of code:

```py
logging.basicConfig(level=logging.DEBUG)

```

这些是严重性级别：

默认的日志记录级别是警告，表示其他消息将被忽略。 如果要打印调试或信息日志消息，则必须更改日志记录级别，如下所示：

| 类型 | 描述 |
| --- | --- |
| 调试 | 仅用于问题诊断的信息 |
| 信息 | 该程序正在按预期运行 |
| 警告 | 指示出了问题 |
| 错误 | 该软件将不再能够运行 |
| 危急 | 非常严重的错误 |

| 

```py
import logging

logging.basicConfig(level=logging.DEBUG)
logging.debug('Debug message')

```

 |

## 记录时间

You can enable time for logging using this line of code:

```py
logging.basicConfig(format='%(asctime)s %(message)s')

```

下面的例子：

```py
import logging

logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
logging.info('Logging app started')
logging.warning('An example logging message.')
logging.warning('Another log message')

```

输出：

```py
2015-06-25 23:24:01,153 Logging app started
2015-06-25 23:24:01,153 An example message.
2015-06-25 23:24:01,153 Another message

```