Skip to content

Logging

pokelance.logger ⚓︎

FileHandler(*, ext, folder='logs') ⚓︎

Bases: FileHandler

Emit a log record.

Parameters:

Name Type Description Default
ext str

The file extension.

required
folder Path | str

The folder to save the logs in. Defaults to "logs".

'logs'

Create a new file handler.

Source code in pokelance/logger.py
Python
def __init__(self, *, ext: str, folder: t.Union[pathlib.Path, str] = "logs") -> None:
    """Create a new file handler."""
    self.folder = pathlib.Path(folder)
    self.ext = ext
    self.folder.mkdir(exist_ok=True)
    super().__init__(
        self.folder / f"{datetime.datetime.today().strftime('%Y-%m-%d')}-{ext}.log",
        encoding="utf-8",
    )
    self.setFormatter(Formatter())

emit(record) ⚓︎

Emit a log record.

Source code in pokelance/logger.py
Python
def emit(self, record: logging.LogRecord) -> None:
    """Emit a log record."""
    if self._last_entry.date() != datetime.datetime.today().date():
        self._last_entry = datetime.datetime.today()
        self.close()
        self.baseFilename = (self.folder / f"{self._last_entry.strftime('%Y-%m-%d')}-{self.ext}.log").as_posix()
        self.stream = self._open()
    super().emit(record)

Formatter() ⚓︎

Bases: Formatter

Format the log record.

Source code in pokelance/logger.py
Python
def __init__(self) -> None:
    super().__init__(
        "[%(asctime)s] | %(pathname)s:%(lineno)d | %(levelname)s | %(message)s",
        style="%",
    )

format(record) ⚓︎

Format the log record.

Source code in pokelance/logger.py
Python
def format(self, record: logging.LogRecord) -> str:
    """Format the log record."""
    return f"{LogLevelColors[record.levelname].value}{super().format(record)}{LogLevelColors.ENDC.value}"

LogLevelColors ⚓︎

Bases: Enum

Colors for the log levels.

Logger(*, name, level=logging.DEBUG, file_logging=False) ⚓︎

Bases: Logger

The logger used to log information about the client.

Parameters:

Name Type Description Default
name str

The name of the logger.

required
level int

The level of the logger.

DEBUG
file_logging bool

Whether or not to log to a file.

False

Attributes:

Name Type Description
_handler StreamHandler

The stream handler used to log to the console.

_file_handler Optional[FileHandler]

The file handler used to log to a file.

Examples:

Python Console Session
>>> logs = Logger(name="pokelance")
>>> logs.info("Hello, world!")
[2021-08-29 17:05:32,000] | pokelance/logger.py:95 | INFO | Hello, world!
Source code in pokelance/logger.py
Python
def __init__(self, *, name: str, level: int = logging.DEBUG, file_logging: bool = False) -> None:
    super().__init__(name, level)
    self._handler = logging.StreamHandler()
    self._handler.addFilter(RelativePathFilter())
    self._handler.setFormatter(Formatter())
    self.addHandler(self._handler)
    if file_logging:
        self._file_handler = FileHandler(ext=name)
        self._file_handler.addFilter(RelativePathFilter())
        self.addHandler(self._file_handler)
    logging.addLevelName(FLAIR, "FLAIR")

flair(message, *args, **kwargs) ⚓︎

Record a flair log.

Source code in pokelance/logger.py
Python
def flair(self, message: str, *args: t.Any, **kwargs: t.Any) -> None:
    """Record a flair log."""
    self.log(FLAIR, message, *args, **kwargs)

set_formatter(formatter) ⚓︎

Set the formatter.

Source code in pokelance/logger.py
Python
def set_formatter(self, formatter: logging.Formatter) -> None:
    """Set the formatter."""
    self._handler.setFormatter(formatter)
    if self._file_handler is not None:
        self._file_handler.setFormatter(formatter)

RelativePathFilter ⚓︎

Bases: Filter

filter(record) ⚓︎

Filter the log record.

Source code in pokelance/logger.py
Python
def filter(self, record: logging.LogRecord) -> bool:
    """Filter the log record."""
    record.pathname = record.pathname.replace(os.getcwd(), "~")
    return True