beans-logging 5.0.0__py3-none-any.whl → 6.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1 @@
1
- # -*- coding: utf-8 -*-
2
-
3
- __version__ = "5.0.0"
1
+ __version__ = "6.0.1"
beans_logging/_base.py CHANGED
@@ -134,8 +134,8 @@ class LoggerLoader:
134
134
  ValueError: The `handler_type` argument value '{handler_type}' is invalid, must be 'NAME' or 'ID'!
135
135
 
136
136
  Args:
137
- handler (str, optional): Handler name or id to remove. Defaults to None.
138
- hadler_type (int, optional): Handler type to remove, must be 'NAME' or 'ID'. Defaults to 'name'.
137
+ handler (str, optional): Handler name or id to remove. Defaults to None.
138
+ handler_type (int, optional): Handler type to remove, must be 'NAME' or 'ID'. Defaults to 'name'.
139
139
  """
140
140
 
141
141
  if handler:
@@ -0,0 +1,419 @@
1
+ Metadata-Version: 2.4
2
+ Name: beans_logging
3
+ Version: 6.0.1
4
+ Summary: 'beans-logging' is a python package for simple logger and easily managing logging.
5
+ Author-email: Batkhuu Byambajav <batkhuu10@gmail.com>
6
+ Project-URL: Homepage, https://github.com/bybatkhuu/module-python-logging
7
+ Project-URL: Documentation, https://pylogging-docs.bybatkhuu.dev
8
+ Project-URL: Repository, https://github.com/bybatkhuu/module-python-logging.git
9
+ Project-URL: Issues, https://github.com/bybatkhuu/module-python-logging/issues
10
+ Project-URL: Changelog, https://github.com/bybatkhuu/module-python-logging/blob/main/CHANGELOG.md
11
+ Keywords: beans_logging,loguru,logging,logger,logs,python-logging,custom-logging
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Requires-Python: <4.0,>=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE.txt
24
+ Requires-Dist: PyYAML<7.0,>=6.0.2
25
+ Requires-Dist: pydantic[timezone]!=2.1.0,<3.0.0,>=2.0.3
26
+ Requires-Dist: loguru<1.0.0,>=0.7.3
27
+ Provides-Extra: fastapi
28
+ Requires-Dist: beans-logging-fastapi<2.0.0,>=1.0.0; extra == "fastapi"
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest<9.0.0,>=8.0.2; extra == "test"
31
+ Requires-Dist: pytest-cov<8.0.0,>=5.0.0; extra == "test"
32
+ Requires-Dist: pytest-xdist<4.0.0,>=3.6.1; extra == "test"
33
+ Requires-Dist: pytest-benchmark<6.0.0,>=5.0.1; extra == "test"
34
+ Provides-Extra: build
35
+ Requires-Dist: setuptools<81.0.0,>=70.3.0; extra == "build"
36
+ Requires-Dist: wheel<1.0.0,>=0.43.0; extra == "build"
37
+ Requires-Dist: build<2.0.0,>=1.1.1; extra == "build"
38
+ Requires-Dist: twine<7.0.0,>=6.0.1; extra == "build"
39
+ Provides-Extra: docs
40
+ Requires-Dist: pylint<4.0.0,>=3.0.4; extra == "docs"
41
+ Requires-Dist: mkdocs-material<10.0.0,>=9.5.50; extra == "docs"
42
+ Requires-Dist: mkdocs-awesome-nav<4.0.0,>=3.0.0; extra == "docs"
43
+ Requires-Dist: mkdocstrings[python]<1.0.0,>=0.24.3; extra == "docs"
44
+ Requires-Dist: mike<3.0.0,>=2.1.3; extra == "docs"
45
+ Provides-Extra: dev
46
+ Requires-Dist: pytest<9.0.0,>=8.0.2; extra == "dev"
47
+ Requires-Dist: pytest-cov<8.0.0,>=5.0.0; extra == "dev"
48
+ Requires-Dist: pytest-xdist<4.0.0,>=3.6.1; extra == "dev"
49
+ Requires-Dist: pytest-benchmark<6.0.0,>=5.0.1; extra == "dev"
50
+ Requires-Dist: setuptools<81.0.0,>=70.3.0; extra == "dev"
51
+ Requires-Dist: wheel<1.0.0,>=0.43.0; extra == "dev"
52
+ Requires-Dist: build<2.0.0,>=1.1.1; extra == "dev"
53
+ Requires-Dist: twine<7.0.0,>=6.0.1; extra == "dev"
54
+ Requires-Dist: pylint<4.0.0,>=3.0.4; extra == "dev"
55
+ Requires-Dist: mkdocs-material<10.0.0,>=9.5.50; extra == "dev"
56
+ Requires-Dist: mkdocs-awesome-nav<4.0.0,>=3.0.0; extra == "dev"
57
+ Requires-Dist: mkdocstrings[python]<1.0.0,>=0.24.3; extra == "dev"
58
+ Requires-Dist: mike<3.0.0,>=2.1.3; extra == "dev"
59
+ Requires-Dist: pyright<2.0.0,>=1.1.392; extra == "dev"
60
+ Requires-Dist: pre-commit<5.0.0,>=4.0.1; extra == "dev"
61
+ Dynamic: license-file
62
+
63
+ # Python Logging (beans-logging)
64
+
65
+ [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit)
66
+ [![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/bybatkhuu/module-python-logging/2.build-publish.yml?logo=GitHub)](https://github.com/bybatkhuu/module-python-logging/actions/workflows/2.build-publish.yml)
67
+ [![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/bybatkhuu/module-python-logging?logo=GitHub&color=blue)](https://github.com/bybatkhuu/module-python-logging/releases)
68
+ [![PyPI](https://img.shields.io/pypi/v/beans-logging?logo=PyPi)](https://pypi.org/project/beans-logging)
69
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/beans-logging?logo=Python)](https://docs.conda.io/en/latest/miniconda.html)
70
+
71
+ `beans-logging` is a python package for simple logger and easily managing logs.
72
+
73
+ It is a `Loguru` based custom logging package for python projects.
74
+
75
+ ## ✨ Features
76
+
77
+ - Main **logger** based on **Loguru** logging - <https://pypi.org/project/loguru>
78
+ - Logging to **log files** (all, error, json)
79
+ - **Pre-defined** logging configs and handlers
80
+ - **Colorful** logging
81
+ - Auto **intercepting** and **muting** modules
82
+ - Load config from **YAML** or **JSON** file
83
+ - Custom options as a **config**
84
+ - Custom logging **formats**
85
+ - **Multiprocess** compatibility (Linux, macOS - 'fork')
86
+ - Add custom **handlers**
87
+ - **Base** logging module
88
+
89
+ ---
90
+
91
+ ## 🛠 Installation
92
+
93
+ ### 1. 🚧 Prerequisites
94
+
95
+ - Install **Python (>= v3.10)** and **pip (>= 23)**:
96
+ - **[RECOMMENDED] [Miniconda (v3)](https://www.anaconda.com/docs/getting-started/miniconda/install)**
97
+ - *[arm64/aarch64] [Miniforge (v3)](https://github.com/conda-forge/miniforge)*
98
+ - *[Python virutal environment] [venv](https://docs.python.org/3/library/venv.html)*
99
+
100
+ [OPTIONAL] For **DEVELOPMENT** environment:
101
+
102
+ - Install [**git**](https://git-scm.com/downloads)
103
+ - Setup an [**SSH key**](https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh) ([video tutorial](https://www.youtube.com/watch?v=snCP3c7wXw0))
104
+
105
+ ### 2. 📥 Download or clone the repository
106
+
107
+ [TIP] Skip this step, if you're going to install the package directly from **PyPi** or **GitHub** repository.
108
+
109
+ **2.1.** Prepare projects directory (if not exists):
110
+
111
+ ```sh
112
+ # Create projects directory:
113
+ mkdir -pv ~/workspaces/projects
114
+
115
+ # Enter into projects directory:
116
+ cd ~/workspaces/projects
117
+ ```
118
+
119
+ **2.2.** Follow one of the below options **[A]**, **[B]** or **[C]**:
120
+
121
+ **OPTION A.** Clone the repository:
122
+
123
+ ```sh
124
+ git clone https://github.com/bybatkhuu/module-python-logging.git && \
125
+ cd module-python-logging
126
+ ```
127
+
128
+ **OPTION B.** Clone the repository (for **DEVELOPMENT**: git + ssh key):
129
+
130
+ ```sh
131
+ git clone git@github.com:bybatkhuu/module-python-logging.git && \
132
+ cd module-python-logging
133
+ ```
134
+
135
+ **OPTION C.** Download source code:
136
+
137
+ 1. Download archived **zip** file from [**releases**](https://github.com/bybatkhuu/module-python-logging/releases).
138
+ 2. Extract it into the projects directory.
139
+
140
+ ### 3. 📦 Install the package
141
+
142
+ [NOTE] Choose one of the following methods to install the package **[A ~ F]**:
143
+
144
+ **OPTION A.** [**RECOMMENDED**] Install from **PyPi**:
145
+
146
+ ```sh
147
+ pip install -U beans-logging
148
+ ```
149
+
150
+ **OPTION B.** Install latest version directly from **GitHub** repository:
151
+
152
+ ```sh
153
+ pip install git+https://github.com/bybatkhuu/module-python-logging.git
154
+ ```
155
+
156
+ **OPTION C.** Install from the downloaded **source code**:
157
+
158
+ ```sh
159
+ # Install directly from the source code:
160
+ pip install .
161
+
162
+ # Or install with editable mode:
163
+ pip install -e .
164
+ ```
165
+
166
+ **OPTION D.** Install for **DEVELOPMENT** environment:
167
+
168
+ ```sh
169
+ pip install -e .[dev]
170
+
171
+ # Install pre-commit hooks:
172
+ pre-commit install
173
+ ```
174
+
175
+ **OPTION E.** Install from **pre-built release** files:
176
+
177
+ 1. Download **`.whl`** or **`.tar.gz`** file from [**releases**](https://github.com/bybatkhuu/module-python-logging/releases)
178
+ 2. Install with pip:
179
+
180
+ ```sh
181
+ # Install from .whl file:
182
+ pip install ./beans_logging-[VERSION]-py3-none-any.whl
183
+
184
+ # Or install from .tar.gz file:
185
+ pip install ./beans_logging-[VERSION].tar.gz
186
+ ```
187
+
188
+ **OPTION F.** Copy the **module** into the project directory (for **testing**):
189
+
190
+ ```sh
191
+ # Install python dependencies:
192
+ pip install -r ./requirements.txt
193
+
194
+ # Copy the module source code into the project:
195
+ cp -r ./src/beans_logging [PROJECT_DIR]
196
+ # For example:
197
+ cp -r ./src/beans_logging /some/path/project/
198
+ ```
199
+
200
+ ## 🚸 Usage/Examples
201
+
202
+ To use `beans_logging`, import the `logger` instance from the `beans_logging.auto` package:
203
+
204
+ ```python
205
+ from beans_logging.auto import logger
206
+ ```
207
+
208
+ You can call logging methods directly from the `logger` instance:
209
+
210
+ ```python
211
+ logger.info("Logging info.")
212
+ ```
213
+
214
+ ### **Simple**
215
+
216
+ [**`configs/logger.yml`**](https://github.com/bybatkhuu/module-python-logging/blob/main/examples/simple/configs/logger.yml):
217
+
218
+ ```yml
219
+ logger:
220
+ app_name: "my-app"
221
+ level: "TRACE"
222
+ file:
223
+ log_handlers:
224
+ enabled: true
225
+ json_handlers:
226
+ enabled: true
227
+ ```
228
+
229
+ [**`main.py`**](https://github.com/bybatkhuu/module-python-logging/blob/main/examples/simple/main.py):
230
+
231
+ ```python
232
+ from beans_logging.auto import logger
233
+
234
+
235
+ logger.trace("Tracing...")
236
+ logger.debug("Debugging...")
237
+ logger.info("Logging info.")
238
+ logger.success("Success.")
239
+ logger.warning("Warning something.")
240
+ logger.error("Error occured.")
241
+ logger.critical("CRITICAL ERROR.")
242
+
243
+ def divide(a, b):
244
+ _result = a / b
245
+ return _result
246
+
247
+ def nested(c):
248
+ try:
249
+ divide(5, c)
250
+ except ZeroDivisionError as err:
251
+ logger.error(err)
252
+ raise
253
+
254
+ try:
255
+ nested(0)
256
+ except Exception as err:
257
+ logger.exception("Show me, what value is wrong:")
258
+ ```
259
+
260
+ Run the [**`examples/simple`**](https://github.com/bybatkhuu/module-python-logging/tree/main/examples/simple):
261
+
262
+ ```sh
263
+ cd ./examples/simple
264
+
265
+ python ./main.py
266
+ ```
267
+
268
+ **Output**:
269
+
270
+ ```txt
271
+ [2023-09-01 00:00:00.000 +09:00 | TRACE | beans_logging._base:478]: Intercepted modules: ['concurrent', 'concurrent.futures', 'asyncio']; Muted modules: [];
272
+ [2023-09-01 00:00:00.000 +09:00 | TRACE | __main__:7]: Tracing...
273
+ [2023-09-01 00:00:00.000 +09:00 | DEBUG | __main__:8]: Debugging...
274
+ [2023-09-01 00:00:00.000 +09:00 | INFO | __main__:9]: Logging info.
275
+ [2023-09-01 00:00:00.000 +09:00 | OK | __main__:10]: Success.
276
+ [2023-09-01 00:00:00.000 +09:00 | WARN | __main__:11]: Warning something.
277
+ [2023-09-01 00:00:00.000 +09:00 | ERROR | __main__:12]: Error occured.
278
+ [2023-09-01 00:00:00.000 +09:00 | CRIT | __main__:13]: CRITICAL ERROR.
279
+ [2023-09-01 00:00:00.000 +09:00 | ERROR | __main__:25]: division by zero
280
+ [2023-09-01 00:00:00.000 +09:00 | ERROR | __main__:32]: Show me, what value is wrong:
281
+ Traceback (most recent call last):
282
+
283
+ > File "/home/user/workspaces/projects/beans_logging/examples/simple/./main.py", line 30, in <module>
284
+ nested(0)
285
+ └ <function nested at 0x10802a4c0>
286
+
287
+ File "/home/user/workspaces/projects/beans_logging/examples/simple/./main.py", line 23, in nested
288
+ divide(5, c)
289
+ │ └ 0
290
+ └ <function divide at 0x1052f31f0>
291
+
292
+ File "/home/user/workspaces/projects/beans_logging/examples/simple/./main.py", line 17, in divide
293
+ _result = a / b
294
+ │ └ 0
295
+ └ 5
296
+
297
+ ZeroDivisionError: division by zero
298
+ ```
299
+
300
+ 👍
301
+
302
+ ---
303
+
304
+ ## ⚙️ Configuration
305
+
306
+ [**`templates/configs/config.yml`**](./templates/configs/config.yml):
307
+
308
+ ```yaml
309
+ logger:
310
+ # app_name: "app"
311
+ level: "INFO"
312
+ use_diagnose: false
313
+ stream:
314
+ use_color: true
315
+ use_icon: false
316
+ format_str: "[<c>{time:YYYY-MM-DD HH:mm:ss.SSS Z}</c> | <level>{level_short:<5}</level> | <w>{name}:{line}</w>]: <level>{message}</level>"
317
+ std_handler:
318
+ enabled: true
319
+ file:
320
+ logs_dir: "./logs"
321
+ rotate_size: 10000000 # 10MB
322
+ rotate_time: "00:00:00"
323
+ backup_count: 90
324
+ log_handlers:
325
+ enabled: false
326
+ format_str: "[{time:YYYY-MM-DD HH:mm:ss.SSS Z} | {level_short:<5} | {name}:{line}]: {message}"
327
+ log_path: "{app_name}.std.all.log"
328
+ err_path: "{app_name}.std.err.log"
329
+ json_handlers:
330
+ enabled: false
331
+ use_custom: false
332
+ log_path: "{app_name}.json.all.log"
333
+ err_path: "{app_name}.json.err.log"
334
+ intercept:
335
+ auto_load:
336
+ enabled: true
337
+ only_base: false
338
+ ignore_modules: []
339
+ include_modules: []
340
+ mute_modules: []
341
+ extra:
342
+ ```
343
+
344
+ ### 🌎 Environment Variables
345
+
346
+ [**`.env.example`**](./.env.example):
347
+
348
+ ```sh
349
+ # ENV=LOCAL
350
+ # DEBUG=false
351
+ # TZ=UTC
352
+
353
+ # BEANS_LOGGING_DISABLE_DEFAULT=false
354
+ # BEANS_LOGGING_CONFIG_PATH="./configs/logger.yml"
355
+ # BEANS_LOGGING_LOGS_DIR="./logs"
356
+ ```
357
+
358
+ ---
359
+
360
+ ## 🧪 Running Tests
361
+
362
+ To run tests, run the following command:
363
+
364
+ ```sh
365
+ # Install python test dependencies:
366
+ pip install .[test]
367
+
368
+ # Run tests:
369
+ python -m pytest -sv -o log_cli=true
370
+ # Or use the test script:
371
+ ./scripts/test.sh -l -v -c
372
+ ```
373
+
374
+ ## 🏗️ Build Package
375
+
376
+ To build the python package, run the following command:
377
+
378
+ ```sh
379
+ # Install python build dependencies:
380
+ pip install -r ./requirements/requirements.build.txt
381
+
382
+ # Build python package:
383
+ python -m build
384
+ # Or use the build script:
385
+ ./scripts/build.sh
386
+ ```
387
+
388
+ ## 📝 Generate Docs
389
+
390
+ To build the documentation, run the following command:
391
+
392
+ ```sh
393
+ # Install python documentation dependencies:
394
+ pip install -r ./requirements/requirements.docs.txt
395
+
396
+ # Serve documentation locally (for development):
397
+ mkdocs serve -a 0.0.0.0:8000
398
+ # Or use the docs script:
399
+ ./scripts/docs.sh
400
+
401
+ # Or build documentation:
402
+ mkdocs build
403
+ # Or use the docs script:
404
+ ./scripts/docs.sh -b
405
+ ```
406
+
407
+ ## 📚 Documentation
408
+
409
+ - [Docs](./docs)
410
+
411
+ ---
412
+
413
+ ## 📑 References
414
+
415
+ - <https://github.com/Delgan/loguru>
416
+ - <https://loguru.readthedocs.io/en/stable/api/logger.html>
417
+ - <https://loguru.readthedocs.io/en/stable/resources/recipes.html>
418
+ - <https://docs.python.org/3/library/logging.html>
419
+ - <https://github.com/bybatkhuu/module-fastapi-logging>
@@ -0,0 +1,17 @@
1
+ beans_logging/__init__.py,sha256=TxuozMCLvGkG7sATP2uFCQws6TRqwp36yc08zUVGcb4,297
2
+ beans_logging/__version__.py,sha256=unmO3xtN2S1e9meUbIjG3AZVyKxUe4HSZNXDOcpZRJg,22
3
+ beans_logging/_base.py,sha256=_4mllOq9hr65Aq7OUkQU3OPTtPvmpv-4x47J6oWN9TI,24573
4
+ beans_logging/_consts.py,sha256=b_-uytryZFCxlD2aKXzdS0oQpAsaK6JLi-w5bUeG1yE,345
5
+ beans_logging/_handlers.py,sha256=WQjr-dGAnjsegI2LHJl_Fubxb0reSCr8A6IvR7eN8dk,1133
6
+ beans_logging/_utils.py,sha256=Smb0cxkTdVxA-IE-oqi3sGhpsQdtNquQSw2bQxN0pDM,2742
7
+ beans_logging/auto.py,sha256=Wyi4w4qZ9PNW2dDF19E8qoKuZVfhyAEl_rVPzMscVCM,534
8
+ beans_logging/filters.py,sha256=YNUF5_0hE0XoPfLCi5wQFe1Qi7eLV0UaJUtCDwlG5ec,3369
9
+ beans_logging/formats.py,sha256=gxyJT9ZUWQvjrL4x6fU5bLKybGsFkCpFDG5OpndqDhc,1349
10
+ beans_logging/rotation.py,sha256=GspZX7wff_igZjbGSysCboz8fUgDHofGRL10OaNlZ3I,2137
11
+ beans_logging/schemas.py,sha256=syMsmwbDvDE1odnaIX18PEIEpWyItfDDnisZr1AsOPs,5641
12
+ beans_logging/sinks.py,sha256=C_y53i_QJuNZs_zBitb87d_tfsLhin2D9DtImPV5OHg,356
13
+ beans_logging-6.0.1.dist-info/licenses/LICENSE.txt,sha256=CUTK-r0BWIg1r0bBiemAcMhakgV0N7HuRhw6rQ-A9A4,1074
14
+ beans_logging-6.0.1.dist-info/METADATA,sha256=qbUyyqgbutJ9qHsPrFge6pIsXUeomPoQB-qkpgYto74,12877
15
+ beans_logging-6.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
16
+ beans_logging-6.0.1.dist-info/top_level.txt,sha256=lx8JEqYGNha1sYbVrTtMo2Z01A7Shq8hX6bfsuKLTG8,14
17
+ beans_logging-6.0.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.41.3)
2
+ Generator: setuptools (80.9.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2023 Batkhuu Byambajav
3
+ Copyright (c) 2025 Batkhuu Byambajav
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -1,6 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
-
3
- from ._filters import use_http_filter
4
- from ._formats import http_file_format, http_file_json_format
5
- from ._handlers import add_http_file_handler, add_http_file_json_handler
6
- from ._middlewares import HttpAccessLogMiddleware
@@ -1,22 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
-
3
- from beans_logging.filters import use_all_filter
4
-
5
-
6
- def use_http_filter(record: dict) -> bool:
7
- """Filter message only for http access log handler by checking 'http_info' key in extra.
8
-
9
- Args:
10
- record (dict): Log record as dictionary.
11
-
12
- Returns:
13
- bool: True if record has 'http_info' key in extra, False otherwise.
14
- """
15
-
16
- if not use_all_filter(record):
17
- return False
18
-
19
- if "http_info" not in record["extra"]:
20
- return False
21
-
22
- return True
@@ -1,62 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
-
3
-
4
- def http_file_format(record: dict) -> str:
5
- """Http access log file format.
6
-
7
- Args:
8
- record (dict): Log record as dictionary.
9
-
10
- Returns:
11
- str: Format for http access log record.
12
- """
13
-
14
- _MSG_FORMAT = '{client_host} {request_id} {user_id} [{datetime}] "{method} {url_path} HTTP/{http_version}" {status_code} {content_length} "{h_referer}" "{h_user_agent}" {response_time}'
15
-
16
- if "http_info" not in record["extra"]:
17
- return ""
18
-
19
- if "http_message" not in record:
20
- _http_info = record["extra"]["http_info"]
21
- if "datetime" not in _http_info:
22
- _http_info["datetime"] = record["time"].isoformat()
23
-
24
- if "content_length" not in _http_info:
25
- _http_info["content_length"] = 0
26
-
27
- if "h_referer" not in _http_info:
28
- _http_info["h_referer"] = "-"
29
-
30
- if "h_user_agent" not in _http_info:
31
- _http_info["h_user_agent"] = "-"
32
-
33
- if "response_time" not in _http_info:
34
- _http_info["response_time"] = 0
35
-
36
- record["extra"]["http_info"] = _http_info
37
-
38
- _msg = _MSG_FORMAT.format(**_http_info)
39
- record["http_message"] = _msg
40
-
41
- return "{http_message}\n"
42
-
43
-
44
- def http_file_json_format(record: dict) -> str:
45
- """Http access json log file format.
46
-
47
- Args:
48
- record (dict): Log record as dictionary.
49
-
50
- Returns:
51
- str: Format for http access json log record.
52
- """
53
-
54
- if "http_info" not in record["extra"]:
55
- return ""
56
-
57
- _http_info = record["extra"]["http_info"]
58
- if "datetime" not in _http_info:
59
- _http_info["datetime"] = record["time"].isoformat()
60
- record["extra"]["http_info"] = _http_info
61
-
62
- return "{extra[http_info]}\n"
@@ -1,79 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
-
3
- from typing import Union, Callable
4
-
5
- import pydantic
6
-
7
- if "2.0.0" <= pydantic.__version__:
8
- from pydantic import validate_call
9
- else:
10
- from pydantic import validate_arguments as validate_call
11
-
12
- from beans_logging import LoggerLoader
13
-
14
- from ._filters import use_http_filter
15
- from ._formats import http_file_format, http_file_json_format
16
-
17
-
18
- @validate_call(config=dict(arbitrary_types_allowed=True))
19
- def add_http_file_handler(
20
- logger_loader: LoggerLoader,
21
- log_path: str = "http/{app_name}.http.access.log",
22
- err_path: str = "http/{app_name}.http.err.log",
23
- formatter: Union[Callable, str] = http_file_format,
24
- ):
25
- """Add http access log file and error file handler.
26
-
27
- Args:
28
- logger_loader (LoggerLoader, required): LoggerLoader instance.
29
- log_path (str, optional): Log file path. Defaults to "http/{app_name}.http.access.log".
30
- err_path (str, optional): Error log file path. Defaults to "http/{app_name}.http.err.log".
31
- formatter (Union[Callable, str], optional): Log formatter. Defaults to `http_file_format` function.
32
- """
33
-
34
- logger_loader.add_custom_handler(
35
- handler_name="FILE.HTTP",
36
- sink=log_path,
37
- filter=use_http_filter,
38
- format=formatter,
39
- )
40
-
41
- logger_loader.add_custom_handler(
42
- handler_name="FILE.HTTP_ERR",
43
- sink=err_path,
44
- level="WARNING",
45
- filter=use_http_filter,
46
- format=formatter,
47
- )
48
-
49
-
50
- @validate_call(config=dict(arbitrary_types_allowed=True))
51
- def add_http_file_json_handler(
52
- logger_loader: LoggerLoader,
53
- log_path: str = "json.http/{app_name}.json.http.access.log",
54
- err_path: str = "json.http/{app_name}.json.http.err.log",
55
- formatter: Union[Callable, str] = http_file_json_format,
56
- ):
57
- """Add http access json log file and json error file handler.
58
-
59
- Args:
60
- logger_loader (LoggerLoader, required): LoggerLoader instance.
61
- log_path (str, optional): Json log file path. Defaults to "http.json/{app_name}.json.http.access.log".
62
- err_path (str, optional): Json error log file path. Defaults to "http.json/{app_name}.json.http.err.log".
63
- formatter (Union[Callable, str], optional): Log formatter. Defaults to `http_file_json_format` function.
64
- """
65
-
66
- logger_loader.add_custom_handler(
67
- handler_name="FILE.JSON.HTTP",
68
- sink=log_path,
69
- filter=use_http_filter,
70
- format=formatter,
71
- )
72
-
73
- logger_loader.add_custom_handler(
74
- handler_name="FILE.JSON.HTTP_ERR",
75
- sink=err_path,
76
- level="WARNING",
77
- filter=use_http_filter,
78
- format=formatter,
79
- )