Skip to main content

utox

个人 Python 工具库:日志、时间、配置、文件读写、装饰器等常用功能。

安装

pip install utox

如需使用 read_file 的 pydantic 模型解析能力,额外安装:

pip install utox[pydantic]

快速开始

日志

from utox import newLog, DEBUG

log = newLog("myapp")            # 控制台彩色输出,默认 INFO 级别
log.info("hello %s", "world")

log = newLog("myapp", level=DEBUG)          # 级别常量(无需 import logging)
log = newLog("myapp", level="DEBUG")        # 也支持级别名字符串,大小写不敏感
log = newLog("myapp", enable_file=True)     # 加文件输出

文件默认写入项目根目录的 logs/ 下,按天命名(2026_08_15.log);午夜自动切换到新日期的文件(长驻进程跨天运行也能正确分文件),仅保留最近 30 天(Log(..., backup_days=N) 可调)。

异常堆栈:

try:
    ...
except Exception:
    log.exception("任务失败")      # ERROR 级别,附带完整堆栈

JSON 结构化日志(供 ELK 等采集系统解析,extra= 字段会合并进 JSON):

log = newLog("myapp", enable_file=True, json_format=True)
log.info("用户登录", extra={"user_id": 42})
# 文件里每行:{"time": "...", "level": "INFO", "logger": "myapp", "message": "用户登录", "user_id": 42}

时间

from utox import str2timestamp, timestamp2str, delta_day

ts = str2timestamp("2024-03-15 13:00:00")   # -> int 时间戳
s = timestamp2str(ts)                        # -> "2024-03-15 13:00:00"
delta_day("2024-03-15 13:00:00")             # -> 46800(当天已过的秒数)

ini 配置

from utox import IniUtil

ini = IniUtil("./conf.ini")
ini.get_value("section", "key")
ini.set_value("section", "key", "value")

文件读写

from utox import read_file, write_file

write_file("data.json", '{"a": 1}')
read_file("data.json")          # -> {"a": 1}

# 传入 pydantic 模型类可自动校验
read_file("data.json", MyModel)

装饰器

from utox import profile, time_it, retry, memoize

@time_it
def slow_func():
    ...

@profile()
def heavy_func():
    ...

@retry(max_retries=3, delay=1, backoff=2, logger=log)   # 失败自动重试(指数退避)
def unstable_api():
    ...

@memoize(ttl=60)               # 结果缓存 60 秒;不传 ttl 则永久缓存
def expensive_query(user_id):
    ...

常用工具

from utox import is_empty, is_not_empty, pre_condition, to_response

is_empty("")        # True
is_not_empty("x")   # True
pre_condition(x > 0, "x 必须大于 0")   # 不满足抛 ValueError
to_response(0, "ok", data)            # {"code": 0, "msg": "ok", "data": data}

API 一览

模块 内容
utox.log Log / newLog:彩色控制台 + 按天滚动文件日志(北京时间);DEBUG/INFO/WARNING/ERROR/CRITICAL 级别常量;exception() 堆栈日志、json_format 结构化日志
utox.timeutil str2timestamp / timestamp2str / delta_day
utox.iniutil IniUtil:ini 配置读写
utox.fileutil read_file / write_file(支持 pydantic 可选解析)
utox.annotationutil profile / time_it / retry(重试)/ memoize(缓存)装饰器
utox.util 空值判断、条件断言、项目根目录探测、区间重叠判断等

开发

pip install -e .[test]
pytest

License

Apache-2.0

Metadata

Release files for utox 0.1.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 utox 0.1.0
File Size Uploaded Provenance Actions
utox-0.1.0.tar.gz 24.1 kB Without provenance Details for utox-0.1.0.tar.gz

Release files / utox-0.1.0.tar.gz

Download URL utox-0.1.0.tar.gz
Size 24.1 kB
Tags Source
SHA-256 checksum
How to use checksums
8e0dd09873956c52365df8a453c0ce41a8217d3956afee201d145685084d3be6
BLAKE2b-256 checksum
How to use checksums
d6a99856a985d1c4cf66268e1a7af9ff78737adeaad97844f6c8fae332d019af
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.6

Security for utox 0.1.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