Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -143,20 +143,21 @@ repos:
files: \.pyi?$
args: ["--skip=B101"] # skip assert-use warning


# - repo: https://github.com/RobertCraigie/pyright-python
# rev: v1.1.404
# hooks:
# - id: pyright
# name: "🐍 pyright - Static type checker"
# files: \.pyi?$

- repo: local
hooks:
- id: pyright
name: "🐍 pyright (local) - Static type checker"
language: system
entry: "python -m pyright"
files: \.pyi?$
# - repo: local
# hooks:
# - id: pyright
# name: "🐍 pyright (local) - Static type checker"
# language: system
# entry: "python -m pyright"
# files: \.pyi?$

# --- Tests ---
# - repo: local
Expand Down
2 changes: 0 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,3 @@


**Full Changelog**: https://github.com/bybatkhuu/module-python-logging/compare/v6.0.0...v6.0.1


17 changes: 11 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ It is a `Loguru` based custom logging package for python projects.
[OPTIONAL] For **DEVELOPMENT** environment:

- Install [**git**](https://git-scm.com/downloads)
- 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))
- Setup an [**SSH key**](https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh)

### 2. 📥 Download or clone the repository

Expand Down Expand Up @@ -151,7 +151,7 @@ logger.info("Logging info.")

### **Simple**

[**`configs/logger.yml`**](https://github.com/bybatkhuu/module-python-logging/blob/main/examples/simple/configs/logger.yml):
[**`configs/logger.yml`**](./examples/simple/configs/logger.yml):

```yml
logger:
Expand All @@ -164,9 +164,11 @@ logger:
enabled: true
```

[**`main.py`**](https://github.com/bybatkhuu/module-python-logging/blob/main/examples/simple/main.py):
[**`main.py`**](./examples/simple/main.py):

```python
#!/usr/bin/env python

from beans_logging.auto import logger


Expand All @@ -178,24 +180,27 @@ logger.warning("Warning something.")
logger.error("Error occured.")
logger.critical("CRITICAL ERROR.")


def divide(a, b):
_result = a / b
return _result


def nested(c):
try:
divide(5, c)
except ZeroDivisionError as err:
logger.error(err)
raise


try:
nested(0)
except Exception as err:
except Exception:
logger.exception("Show me, what value is wrong:")
```

Run the [**`examples/simple`**](https://github.com/bybatkhuu/module-python-logging/tree/main/examples/simple):
Run the [**`examples/simple`**](./examples/simple):

```sh
cd ./examples/simple
Expand Down Expand Up @@ -241,7 +246,7 @@ ZeroDivisionError: division by zero

## ⚙️ Configuration

[**`templates/configs/config.yml`**](./templates/configs/config.yml):
[**`templates/configs/logger.yml`**](./templates/configs/logger.yml):

```yaml
logger:
Expand Down
4 changes: 2 additions & 2 deletions docs/getting-started/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ title: Configuration

# ⚙️ Configuration

[**`templates/configs/config.yml`**](https://github.com/bybatkhuu/module-python-logging/blob/main/templates/configs/config.yml):
[**`templates/configs/logger.yml`**](https://github.com/bybatkhuu/module-python-logging/blob/main/templates/configs/logger.yml):

```yaml
--8<-- "./templates/configs/config.yml"
--8<-- "./templates/configs/logger.yml"
```

## 🌎 Environment Variables
Expand Down
2 changes: 1 addition & 1 deletion docs/getting-started/prerequisites.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ title: Prerequisites
[OPTIONAL] For **DEVELOPMENT** environment:

- Install [**git**](https://git-scm.com/downloads)
- 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))
- Setup an [**SSH key**](https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh)
2 changes: 0 additions & 2 deletions docs/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,3 @@ hide:


**Full Changelog**: https://github.com/bybatkhuu/module-python-logging/compare/v6.0.0...v6.0.1


2 changes: 1 addition & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
site_name: Python Logging (beans-logging)
site_description: "'beans-logging' is a python package for simple logger and easily managing logging."
site_description: "'beans-logging' is a python package for simple logger and easily managing logs."
site_url: https://pylogging-docs.bybatkhuu.dev
repo_name: bybatkhuu/module-python-logging
repo_url: https://github.com/bybatkhuu/module-python-logging
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "beans_logging"
authors = [{ name = "Batkhuu Byambajav", email = "batkhuu10@gmail.com" }]
description = "'beans-logging' is a python package for simple logger and easily managing logging."
description = "'beans-logging' is a python package for simple logger and easily managing logs."
readme = "README.md"
requires-python = ">=3.10,<4.0"
keywords = [
Expand Down
2 changes: 0 additions & 2 deletions src/beans_logging/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

from ._base import Logger, logger, LoggerLoader
from .schemas import LoggerConfigPM
from ._consts import WarnEnum
Expand Down
74 changes: 35 additions & 39 deletions src/beans_logging/_base.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
# -*- coding: utf-8 -*-

## Standard libraries
# Standard libraries
import os
import copy
import json
import logging
from typing import Union, Dict, Any
from typing import Any

## Third-party libraries
# Third-party libraries
import yaml
from loguru import logger
from loguru._logger import Logger
Expand All @@ -18,7 +16,7 @@
else:
from pydantic import validate_arguments as validate_call

## Internal modules
# Internal modules
from ._utils import create_dir, deep_merge
from ._handlers import InterceptHandler
from .rotation import RotationChecker
Expand Down Expand Up @@ -67,20 +65,22 @@ class LoggerLoader:
@validate_call
def __init__(
self,
config: Union[LoggerConfigPM, Dict[str, Any], None] = None,
config: LoggerConfigPM | dict[str, Any] | None = None,
config_file_path: str = _CONFIG_FILE_PATH,
auto_config_file: bool = True,
auto_load: bool = False,
):
"""LoggerLoader constructor method.

Args:
config (Union[LoggerConfigPM,
dict,
None ], optional): New logger config to update loaded config. Defaults to None.
config_file_path (str , optional): Logger config file path. Defaults to `LoggerLoader._CONFIG_FILE_PATH`.
auto_config_file (bool , optional): Indicates whether to load logger config file or not. Defaults to True.
auto_load (bool , optional): Indicates whether to load logger handlers or not. Defaults to False.
config (LoggerConfigPM | dict | None], optional): New logger config to update loaded config.
Defaults to None.
config_file_path (str , optional): Logger config file path. Defaults to
`LoggerLoader._CONFIG_FILE_PATH`.
auto_config_file (bool , optional): Indicates whether to load logger config
file or not. Defaults to True.
auto_load (bool , optional): Indicates whether to load logger
handlers or not. Defaults to False.
"""

self.handlers_map = {"default": 0}
Expand Down Expand Up @@ -125,9 +125,7 @@ def load(self) -> Logger:
return logger

@validate_call
def remove_handler(
self, handler: Union[str, None] = None, handler_type: str = "NAME"
):
def remove_handler(self, handler: str | None = None, handler_type: str = "NAME"):
"""Remove all handlers or specific handler by name or id from logger.

Raises:
Expand Down Expand Up @@ -162,7 +160,7 @@ def remove_handler(
self.handlers_map.clear()

@validate_call
def update_config(self, config: Union[LoggerConfigPM, Dict[str, Any]]):
def update_config(self, config: LoggerConfigPM | dict[str, Any]):
"""Update logger config with new config.

Args:
Expand Down Expand Up @@ -213,13 +211,11 @@ def _load_config_file(self):
# elif self.config_file_path.lower().endswith(".toml"):
# _file_format = "TOML"

## Loading config from file, if it's exits:
# Loading config from file, if it's exits:
if os.path.isfile(self.config_file_path):
if _file_format == "YAML":
try:
with open(
self.config_file_path, "r", encoding="utf-8"
) as _config_file:
with open(self.config_file_path, encoding="utf-8") as _config_file:
_new_config_dict = yaml.safe_load(_config_file) or {}
if "logger" not in _new_config_dict:
logger.warning(
Expand All @@ -242,9 +238,7 @@ def _load_config_file(self):
raise
elif _file_format == "JSON":
try:
with open(
self.config_file_path, "r", encoding="utf-8"
) as _config_file:
with open(self.config_file_path, encoding="utf-8") as _config_file:
_new_config_dict = json.load(_config_file) or {}
if "logger" not in _new_config_dict:
logger.warning(
Expand Down Expand Up @@ -296,7 +290,7 @@ def _load_config_file(self):
def _check_env(self):
"""Check environment variables for logger config."""

## Checking environment for DEBUG option:
# Checking environment for DEBUG option:
_is_debug = False
_ENV = str(os.getenv("ENV")).strip().lower()
_DEBUG = str(os.getenv("DEBUG")).strip().lower()
Expand All @@ -314,7 +308,7 @@ def _check_env(self):
self.config.file.logs_dir = os.getenv("BEANS_LOGGING_LOGS_DIR")

# if self.config.stream.use_color:
# ## Checking terminal could support xterm colors:
# # Checking terminal could support xterm colors:
# _TERM = str(os.getenv("TERM")).strip()
# if not "xterm" in _TERM:
# self.config.stream.use_color = False
Expand Down Expand Up @@ -536,7 +530,7 @@ def _load_intercept_handlers(self):

_intercept_handler = InterceptHandler()

## Intercepting all logs from standard (root logger) logging:
# Intercepting all logs from standard (root logger) logging:
logging.basicConfig(handlers=[_intercept_handler], level=0, force=True)

_intercepted_modules = set()
Expand Down Expand Up @@ -579,10 +573,10 @@ def _load_intercept_handlers(self):
f"Intercepted modules: {list(_intercepted_modules)}; Muted modules: {list(_muted_modules)};"
)

### ATTRIBUTES ###
## handlers_map ##
# ATTRIBUTES #
# handlers_map
@property
def handlers_map(self) -> Dict[str, int]:
def handlers_map(self) -> dict[str, int]:
try:
return self.__handlers_map
except AttributeError:
Expand All @@ -591,17 +585,17 @@ def handlers_map(self) -> Dict[str, int]:
return self.__handlers_map

@handlers_map.setter
def handlers_map(self, handlers_map: Dict[str, int]):
def handlers_map(self, handlers_map: dict[str, int]):
if not isinstance(handlers_map, dict):
raise TypeError(
f"`handlers_map` attribute type {type(handlers_map)} is invalid, must be <dict>!."
)

self.__handlers_map = copy.deepcopy(handlers_map)

## handlers_map ##
# handlers_map

## config ##
# config
@property
def config(self) -> LoggerConfigPM:
try:
Expand All @@ -620,9 +614,9 @@ def config(self, config: LoggerConfigPM):

self.__config = copy.deepcopy(config)

## config ##
# config

## config_file_path ##
# config_file_path
@property
def config_file_path(self) -> str:
try:
Expand All @@ -648,17 +642,19 @@ def config_file_path(self, config_file_path: str):
):
if not config_file_path.lower().endswith(".toml"):
raise NotImplementedError(
f"`config_file_path` attribute value '{config_file_path}' is invalid, TOML file format is not supported yet!"
f"`config_file_path` attribute value '{config_file_path}' is invalid, "
f"TOML file format is not supported yet!"
)

raise ValueError(
f"`config_file_path` attribute value '{config_file_path}' is invalid, file must be '.yml', '.yaml' or '.json' format!"
f"`config_file_path` attribute value '{config_file_path}' is invalid, "
f"file must be '.yml', '.yaml' or '.json' format!"
)

if not os.path.isabs(config_file_path):
config_file_path = os.path.join(os.getcwd(), config_file_path)

self.__config_file_path = config_file_path

## config_file_path ##
### ATTRIBUTES ###
# config_file_path
# ATTRIBUTES #
2 changes: 0 additions & 2 deletions src/beans_logging/_consts.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

from enum import Enum


Expand Down
6 changes: 2 additions & 4 deletions src/beans_logging/_handlers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

import sys
import logging
from logging import LogRecord
Expand All @@ -25,13 +23,13 @@ def emit(self, record: LogRecord):
record (LogRecord, required): Log needs to be handled.
"""

## Get corresponding Loguru level if it exists
# Get corresponding Loguru level if it exists
try:
_level = logger.level(record.levelname).name
except ValueError:
_level = record.levelno

## Find caller from where originated the logged message
# Find caller from where originated the logged message
_frame, _depth = sys._getframe(6), 6
while _frame and _frame.f_code.co_filename == logging.__file__:
_frame = _frame.f_back
Expand Down
5 changes: 2 additions & 3 deletions src/beans_logging/_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-

import os
import sys
import copy
Expand All @@ -22,7 +20,8 @@ def create_dir(create_dir: str, warn_mode: WarnEnum = WarnEnum.DEBUG):

Args:
create_dir (str, required): Create directory path.
warn_mode (str, optional): Warning message mode, for example: 'ERROR', 'ALWAYS', 'DEBUG', 'IGNORE'. Defaults to "DEBUG".
warn_mode (str, optional): Warning message mode, for example: 'ERROR', 'ALWAYS', 'DEBUG', 'IGNORE'.
Defaults to "DEBUG".
"""

if not os.path.isdir(create_dir):
Expand Down
Loading