SoFunction
Updated on 2024-11-10

Python loguru logging library for efficient output of console logs and log records

1 Install loguru

The PyPI address for loguru is:/project/loguru/

The GitHub repository address is:/Delgan/loguru

We can install it directly using the pip command.

pip install loguru

Or download its source code and install it using Python commands.

|2loguru simple to use

from loguru import logger

("Chinese loguru")
("Chinese loguru")
("Chinese loguru")
("Chinese loguru")

# Running results

2020-03-07 15:51:05.752 | INFO | __main__:info:23 - Chinese loguru
2020-03-07 15:51:05.753 | DEBUG | __main__:debug:26 - Chinese loguru
2020-03-07 15:51:05.753 | WARNING | __main__:warning:29 - Chinese loguru
2020-03-07 15:51:05.753 | ERROR | __main__:error:32 - Chinese loguru

You can see that its default output format contains [time, level, module name, line number and log information], do not need to manually create a logger, direct use can be used, in addition to its output is still colored, it will look more friendly.

|3loguru Retention Log Files

In general, we need to save the log output to a file, loguru directly through the add() method, you can configure a log file, as shown in the following code:

# coding:utf-8
from loguru import logger

("interface_log_{time}.log", rotation="500MB", encoding="utf-8", enqueue=True, compression="zip", retention="10 days")
("Chinese test")
("Chinese test")
("Chinese test")
("Chinese test")

# Then it's off to interface_log_2020-03-07-15: to view the logs

# Include knowledge points
-The first parameter is the path to the file where the log information is stored, like the one I wrote is suffixed with a {time}, which is the current time node, so that a new log will be created automatically; this time should be a variable that comes with the library, if you want to define your own time, you can also Oh, you can look at the following wrapper class to realize the form of specific!
-When you need to output Chinese logs, please add encoding="utf-8" to avoid garbled code.
-enqueue=True for asynchronous writing, the official meaning is: in the multi-process simultaneous log file to write logs when the use of queues to achieve asynchronous efficiency
-rotation can be interpreted as the timing of log creation, and can be written in various ways ◦rotation="500 MB": when the log file reaches 500 MB, a new file will be created.
◦rotation="12:00" : A new file is created at 12:00 every day,
◦rotation="1 week" : create a log every other week

-retention Configure the maximum retention time for logs, official examples: "1 week, 3 days", "2 months".
-compression Configure the compression format of the file, you can configure common formats zip, tar, gz, etc.

|4loguru String Output

Most importantly! loguru also provides the ability to output logs in string format, as in the following code

('If you are using Python {}, prefer {feature} of course!', 3.6, feature='f-strings')
n1 = "cool"
n2 = [1, 2, 3]
(f'If you are using Python {n1}, prefer {n2} of course!')

# Running results

2020-03-07 16:19:25.363 | INFO     | __main__:<module>:43 - If you are using Python 3.6, prefer f-strings of course!
2020-03-07 16:19:25.364 | INFO     | __main__:<module>:46 - If you are using Python cool, prefer [1, 2, 3] of course!

As you can see, as long as you know Python string formatting output, this is a snap!

|5loguru wrapper class, you can take it directly!

Log output path: under the log folder in your project path

Note: This is a tool class, you need to be placed in the project path under the util folder and so on, can not be placed directly under the project path ha, otherwise the path will generate the error Oh!

"""
Operation logging
"""
import time
from loguru import logger
from pathlib import Path

project_path = ().parent
log_path = Path(project_path, "log")
t = ("%Y_%m_%d")

class Loggings:
 __instance = None
 (f"{log_path}/interface_log_{t}.log", rotation="500MB", encoding="utf-8", enqueue=True,
    retention="10 days")

 def __new__(cls, *args, **kwargs):
  if not cls.__instance:
   cls.__instance = super(Loggings, cls).__new__(cls, *args, **kwargs)

  return cls.__instance

 def info(self, msg):
  return (msg)

 def debug(self, msg):
  return (msg)

 def warning(self, msg):
  return (msg)

 def error(self, msg):
  return (msg)


loggings = Loggings()
if __name__ == '__main__':
 ("Chinese test")
 ("Chinese test")
 ("Chinese test")
 ("Chinese test")

 ('If you are using Python {}, prefer {feature} of course!', 3.6, feature='f-strings')
 n1 = "cool"
 n2 = [1, 2, 3]
 (f'If you are using Python {n1}, prefer {n2} of course!')

summarize

To this point this article on Python loguru log library, efficient output console logs and logging article is introduced to this, more related loguru log library, efficient output console logs and logging content, please search my previous posts or continue to browse the following related articles I hope you will support me in the future more!