Merge pull request #17623 from geekpi/translating

translated
This commit is contained in:
geekpi 2020-03-04 08:25:46 +08:00 committed by GitHub
commit 79592285b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 155 additions and 156 deletions

View File

@ -1,156 +0,0 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Use logzero for simple logging in Python)
[#]: via: (https://opensource.com/article/20/2/logzero-python)
[#]: author: (Ben Nuttall https://opensource.com/users/bennuttall)
Use logzero for simple logging in Python
======
A quick primer on the handy log library that can help you master this
important programming concept.
![Snake charmer cartoon with a yellow snake and a blue snake][1]
The logzero library makes logging as easy as a print statement, which is quite a feat of simplicity. I'm not sure whether logzero took its name to fit in with the series of "zero boilerplate" libraries like pygame-zero, GPIO Zero, and guizero, but it's certainly in that category. It's a Python library that makes logging straightforward.
You can just use its basic logging to stdout the same way you might use print for information and debugging purposes, and it has a smooth learning curve towards more advanced logging, like logging to a file.
To start, install logzero with pip:
```
`$ sudo pip3 install logzero`
```
Now in a Python file, import logger and try one or all of these logging examples:
```
from logzero import logger
logger.debug("hello")
logger.info("info")
logger.warning("warning")
logger.error("error")
```
The output is automatically colored in an easy-to-read way:
![Python, Raspberry Pi: import logger][2]
So now, instead of using **print** to figure out what's going on, use logger instead, with the relevant log level.
### Writing logs to a file in Python
If you only read this far and make that one change in the way you write code, that's good enough for me. If you want to go further, read on!
Writing to **stdout** is fun for testing a new program, but it is only useful if you are logged into the computer where the script is running. Many times when using an application you'll want to execute the code remotely and review errors after the fact. That's when it's helpful to log to a file instead. Let's try it:
```
from logzero import logger, logfile
logfile('/home/pi/test.log')
```
Now your log entries will be logged into the file **test.log**. Remember to make sure that the [script has permission][3] to write to that file and its directory structure.
You can specify some more options too:
```
`logfile(/home/pi/test.log, maxBytes=1e6, backupCount=3)`
```
Now when the file provided to **logfile** reaches 1MB (1×106 bytes), it will rotate entries through **test.log.1**, **test.log.2**, and so on. This behavior is nice to avoid generating a massive log file that is I/O intensive for the system to open and close. You might also want to log to **/var/log** like a pro. Assuming you're on Linux, you a directory and make your user the owner so they can write to it:
```
$ sudo mkdir /var/log/test
$ sudo chown pi /var/log/test
```
Then in your Python code, change the **logfile** path:
```
`logfile(/var/log/test/test.log, maxBytes=1e6, backupCount=3)`
```
When it comes to catching exceptions in your **logfile**, you can either use **logging.exception:**
```
try:
    c = a / b
except Exception as e:
    logger.exception(e)
```
This will produce the following (in the case that b is zero):
```
[E 190422 23:41:59 test:9] division by zero
     Traceback (most recent call last):
       File "test.py", line 7, in
         c = a / b
     ZeroDivisionError: division by zero
```
You get the log entry, followed by the full traceback. Alternatively, you could use **logging.error** and hide the traceback:
```
try:
    c = a / b
except Exception as e:
    logger.error(f"{e.__class__.__name__}: {e}")
```
Now this will produce the more succinct:
```
`[E 190423 00:04:16 test:9] ZeroDivisionError: division by zero`
```
* * *
* * *
* * *
**![Logging output][4]**
There are plenty more options which you can read in the docs at [logzero.readthedocs.io][5].
### logzero shines for education
Logging can be a challenging concept for a new programmer. Most frameworks depend on flow control and lots of variable manipulation to make a meaningful log, but logzero is different. With its syntax being similar to a print statement, it is a big win for education as it saves from explaining another concept. Give it a try on your next project.
\--
_This article was originally written on [my blog][6] and is republished with permission._
--------------------------------------------------------------------------------
via: https://opensource.com/article/20/2/logzero-python
作者:[Ben Nuttall][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/bennuttall
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/getting_started_with_python.png?itok=MFEKm3gl (Snake charmer cartoon with a yellow snake and a blue snake)
[2]: https://opensource.com/sites/default/files/uploads/rpi_ben_1.png (Python, Raspberry Pi: import logger)
[3]: https://opensource.com/article/19/6/understanding-linux-permissions
[4]: https://opensource.com/sites/default/files/uploads/rpi_ben_2.png (Logging output)
[5]: https://logzero.readthedocs.io/en/latest/
[6]: https://tooling.bennuttall.com/logzero/

View File

@ -0,0 +1,155 @@
[#]: collector: (lujun9972)
[#]: translator: (geekpi)
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (Use logzero for simple logging in Python)
[#]: via: (https://opensource.com/article/20/2/logzero-python)
[#]: author: (Ben Nuttall https://opensource.com/users/bennuttall)
使用 logzero 在 Python 中进行简单日志记录
======
一个方便的日志库快速入门,来帮助你掌握这个重要的编程概念。
![Snake charmer cartoon with a yellow snake and a blue snake][1]
logzero 库使日志记录就像打印语句一样容易,是简单性的杰出代表。我不确定 logzero 的名称是否要与 pygame-zero、GPIO Zero 和 guizero 这样的 “zero 样板库”契合,但是肯定属于该类别。它是一个 Python 库,使得日志记录变得简单明了。
你可以使用它的基本日志记录到标准输出,就像你可以使用 print 来获得信息和调试一样,它还有学习更高级日志记录(例如记录到文件)的平滑学习曲线。
首先,使用 pip 安装 logzero
```
`$ sudo pip3 install logzero`
```
在 Python 文件中,导入 logger 并尝试以下一个或所有日志实例:
```
from logzero import logger
logger.debug("hello")
logger.info("info")
logger.warning("warning")
logger.error("error")
```
输出以易于阅读的方式自动着色:
![Python, Raspberry Pi: import logger][2]
因此现在不要再使用 **print** 来了解发生了什么,而应使用有相关日志级别的 logger。
### 在 Python 中将日志写入文件
如果你阅读至此,并会在你写代码时做一点改变,这对我就足够了。如果你要了解更多,请继续阅读!
写到**标准输出**对于测试新程序不错,但是仅当你登录到运行脚本的计算机时才有用。在很多时候,你需要远程执行代码并在事后查看错误。这种情况下,记录到文件很有帮助。让我们尝试一下:
```
from logzero import logger, logfile
logfile('/home/pi/test.log')
```
现在,你的日志条目将记录到文件 **test.log** 中。记住确保[脚本有权限] [3]写入该文件及其目录结构。
你也可以指定更多选项:
```
`logfile(/home/pi/test.log, maxBytes=1e6, backupCount=3)`
```
现在,当提供给 **logfile** 文件达到 1MB10^6 字节)时,它将通过 **test.log.1**、**test.log.2** 等文件轮询写入。这种行为可以避免系统打开和关闭大量 I/O 密集的日志文件,以至于系统无法打开和关闭。你或许还要记录到 **/var/log**。假设你使用的是 Linux那么创建一个目录并将用户设为所有者以便可以写入该目录
```
$ sudo mkdir /var/log/test
$ sudo chown pi /var/log/test
```
然后在你的 Python 代码中,更改 **logfile** 路径:
```
`logfile(/var/log/test/test.log, maxBytes=1e6, backupCount=3)`
```
当要在 **logfile** 中捕获异常时,可以使用 **logging.exception**:。
```
try:
    c = a / b
except Exception as e:
    logger.exception(e)
```
这将输出(在 b 为零的情况下):
```
[E 190422 23:41:59 test:9] division by zero
     Traceback (most recent call last):
       File "test.py", line 7, in
         c = a / b
     ZeroDivisionError: division by zero
```
你会得到日志,还有完整回溯。另外,你可以使用 **logging.error** 并隐藏回溯:
```
try:
    c = a / b
except Exception as e:
    logger.error(f"{e.__class__.__name__}: {e}")
```
现在,将产生更简洁的结果:
```
`[E 190423 00:04:16 test:9] ZeroDivisionError: division by zero`
```
* * *
* * *
* * *
**![Logging output][4]**
你可以在 [logzero.readthedocs.io] [5] 中阅读更多选项。
### logzero 为教育而生
对于新手程序员来说,日志记录可能是一个具有挑战性的概念。大多数框架依赖于流控制和大量变量操作来生成有意义的日志,但是 logzero不同。由于它的语法类似于 print 语句,因此它在教育上很成功,因为它无需解释其他概念。在你的下个项目中试试它。
\--
_此文章最初发布在[我的博客] [6]上经许可重新发布。_
--------------------------------------------------------------------------------
via: https://opensource.com/article/20/2/logzero-python
作者:[Ben Nuttall][a]
选题:[lujun9972][b]
译者:[geekpi](https://github.com/geekpi)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/bennuttall
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/getting_started_with_python.png?itok=MFEKm3gl (Snake charmer cartoon with a yellow snake and a blue snake)
[2]: https://opensource.com/sites/default/files/uploads/rpi_ben_1.png (Python, Raspberry Pi: import logger)
[3]: https://opensource.com/article/19/6/understanding-linux-permissions
[4]: https://opensource.com/sites/default/files/uploads/rpi_ben_2.png (Logging output)
[5]: https://logzero.readthedocs.io/en/latest/
[6]: https://tooling.bennuttall.com/logzero/