Skip to main content

Logkk

易于使用且线程安全的日志模块

安装

pip install logkk

基础使用:

from logkk import LogManager

log_manager = LogManager()
log_manager.info("this is a info log")
log_manager.warn("this is a warn log")

logger = log_manager.get_logger(name="hello")
logger.info("this is a info log")
logger.warn("this is a warn log")

使用文件记录日志:

from logkk import LogManager, Level
from logkk.handlers import FileHandler

fmt = "[{datetime}] [{level}] [{name}] {message}"
handler = FileHandler(filepath="/var/log/demo.log")
log_manager = LogManager(level=Level.INFO, fmt=fmt, handlers=[handler])
logger = log_manager.get_logger(name="hello")
logger.info("this is a info log")
logger.warn("this is a warn log")

作为函数装饰器使用

给每个函数添加装饰器,打印函数的参数和返回值,在程序调试阶段是非常好用的。

def log_required(f):

    def func(f2):

        @wraps(f2)
        def decorated(request, *args, **kwargs):
            name = f"{f.__module__}:{f.__name__}"
            logger = log.get_logger(name=name)
            logger.info(f"{request.method} {request.path}")
            logger.info("params=", request.body)
            setattr(request, "logger", logger)
            r = f(request, *args, **kwargs)
            if isinstance(r, BaseResponse):
                logger.info("response=", r.result)
            else:
                logger.info("response=", r)
            return r

        return decorated

    return func(f)


@log_required
def UpdateMyInfoHandler(request: HttpRequest):
    # ...
    return {"code": 0, "message":"OK"}

技术方案说明

写日志文件主要有两种方式:

  1. 每次写日志时打开文件,写完后关闭文件;
  2. 保持一个文件句柄,每次写日志时直接写入文件;

很明显,第二种方式效率更高,但是一直保持一个打开的文件对象,会不会有问题呢?
查询了一些资料后发现,并没有什么问题,因为:

当进程退出时,不管是正常退出还是异常退出,亦或是进程被强制杀掉,操作系统都会回收给进程分配的资源, 也就是说系统会关闭这个文件句柄。

当进程异常退出时,为了保证我们写的日志不丢失,每次写日志时需要调用flush将日志落盘。因为write只是将内容写到系统缓冲区,并没有写到磁盘上, 当进程异常退出时,系统缓冲区的数据会丢失,而flush就是将系统缓冲区的内容写到磁盘上,并清空系统缓冲区。

另外,如果多线程写日志,会出现写入混乱的情况,所以需要加锁,虽然这样会影响效率,但是更加安全可靠。

Metadata

Release files for logkk 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for logkk 0.7.0
File Size Uploaded Provenance Actions
logkk-0.7.0.tar.gz 4.4 kB Without provenance Details for logkk-0.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for logkk 0.7.0
File Interpreter ABI Platform Actions
logkk-0.7.0-py3-none-any.whl Python 3 none any Details for logkk-0.7.0-py3-none-any.whl

Total release size: 9.7 kB

Release files / logkk-0.7.0.tar.gz

Download URL logkk-0.7.0.tar.gz
Size 4.4 kB
Tags Source
SHA-256 checksum
How to use checksums
79057a55baed45886bf6c03399797a9752508233bc654ac34d22bec4dfd0a75f
BLAKE2b-256 checksum
How to use checksums
de1287019e2007529b5ffa042b093fbadce7da223c6d45510a66fa2628f76e59
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.18

Release files / logkk-0.7.0-py3-none-any.whl

Download URL logkk-0.7.0-py3-none-any.whl
Size 5.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b34717474b403694061837b73e9a94aec964f8849da050de4d4d8c33bbc14ba5
BLAKE2b-256 checksum
How to use checksums
130acfa25303bec37a84916838671bdbcecc6a95d7f155e25319a29d7898fed7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.18

Security for logkk 0.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page