Metadata-Version: 2.4
Name: utox
Version: 0.1.0
Summary: 我的 Python 工具库：日志、时间、配置、文件读写、装饰器等
Home-page: https://github.com/bme6/utox
Author: ly
Author-email: 2662017230@qq.com
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: License :: OSI Approved :: Apache Software License
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: pydantic
Requires-Dist: pydantic>=1.10; extra == "pydantic"
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license-file
Dynamic: provides-extra
Dynamic: requires-python
Dynamic: summary

# utox

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

## 安装

```bash
pip install utox
```

如需使用 `read_file` 的 pydantic 模型解析能力，额外安装：

```bash
pip install utox[pydantic]
```

## 快速开始

### 日志

```python
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)` 可调）。

异常堆栈：

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

JSON 结构化日志（供 ELK 等采集系统解析，`extra=` 字段会合并进 JSON）：

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

### 时间

```python
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 配置

```python
from utox import IniUtil

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

### 文件读写

```python
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)
```

### 装饰器

```python
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):
    ...
```

### 常用工具

```python
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` | 空值判断、条件断言、项目根目录探测、区间重叠判断等 |

## 开发

```bash
pip install -e .[test]
pytest
```

## License

[Apache-2.0](LICENSE)
