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
File renamed without changes.
3 changes: 2 additions & 1 deletion src/fusion_logger/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .core import FusionLogger
from .core import FusionLogger, FusionLoggerBuilder
from .defs import FusionLogLevel, FusionLogRecord
from .processors import FusionLogFormatter

Expand All @@ -7,4 +7,5 @@
'FusionLogRecord',
'FusionLogLevel',
'FusionLogFormatter',
'FusionLoggerBuilder',
]
198 changes: 106 additions & 92 deletions src/fusion_logger/core.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,35 @@
"""
Module: core
---------------------

This module implements a flexible and configurable logging component for Python applications.
It provides two main classes:

1. fusion_logger:
- The central logging component that supports configurable scopes and log levels.
- Automatically gathers system metadata such as hostname, process ID, and current thread ID.
- Supports logging methods at various levels (debug, info, warning, critical) by creating
FusionLogRecord instances enriched with metadata.
- Delegates log record processing to a FusionLogProcessor, and formats log entries using a
FusionLogFormatter.
- Allows dynamic configuration of the current logging scope and minimum log level.

2. FusionLoggerBuilder:
- Implements a fluent builder pattern to facilitate the creation and configuration of
fusion_logger instances.
- Provides chainable methods for setting the logger name, minimum log level, and custom
formatter.
- Finalizes and returns a fully configured fusion_logger instance using the build() method.

Dependencies:
- os, socket, threading, and time from the standard library.
- FusionLogLevel and FusionLogRecord from the local 'defs' module.
- FusionLogFormatter and FusionLogProcessor from the local 'processors' module.
---------------
This module provides a centralized logging framework with configurable scopes and levels,
allowing applications to log messages with different severities and custom output destinations.
It integrates system metadata (such as hostname, process ID, and thread ID) into each log record
and supports dynamic log scoping.

Key Components:
----------------
1. FusionLogger: \r\n
- A core logging class that handles logging at various levels (DEBUG, INFO, WARNING, CRITICAL).
- Maintains system information (hostname, process ID, thread ID) and a set of file paths for logging output.
- Supports setting a logging scope via the `begin_scope` and `end_scope` methods.
- Uses a FusionLogProcessor to process log records and a FusionLogFormatter to format them.
- The internal method `__log` creates a FusionLogRecord with the provided information and delegates
processing to the FusionLogProcessor.

2. FusionLoggerBuilder: \r\n
- Implements a fluent builder pattern to simplify the configuration of FusionLogger instances.
- Provides chainable methods to set the logger’s name, minimum logging level, custom formatter, and
file output paths (both individually and in batches).
- The `build` method returns a fully configured FusionLogger instance.
- This builder allows users to configure the logger in a concise and readable manner.

Usage:
Use fusion_logger for logging messages with rich contextual metadata and configurable
behavior.
For ease of configuration, instantiate a FusionLoggerBuilder to set up the logger with the
desired properties and then build the logger instance.
------
The module is designed to be integrated into applications requiring detailed logging functionality.
Users can either work directly with FusionLogger or use FusionLoggerBuilder for a more fluent configuration
process. The logging framework depends on other modules (.defs and .processors)
for log level definitions, record structures, formatting, and processing logic, and it leverages standard
libraries (os, socket, threading, time) to gather system metadata and support concurrency.
"""

import os
Expand All @@ -42,20 +41,20 @@
from fusion_logger.processors import FusionLogFormatter, FusionLogProcessor


class FusionLogger():
class FusionLogger:
"""
Zentrale Logging-Komponente mit konfigurierbaren Scopes und Leveln.
Central logging component with configurable scopes and levels.

Attributes:
name (str): Logger-Identifikation (Standard: Klassenname)
scope (str): Aktiver Logging-Kontextbereich
min_level (FusionLogLevel): Minimale Ausgabestufe für Logs
formatter (FusionLogFormatter): Formatierungskomponente für Logeinträge
name (str): Logger identification (default: class name)
scope (str): Active logging context scope
min_level (FusionLogLevel): Minimum output level for logs
formatter (FusionLogFormatter): Log entry formatting component
"""

def __init__(self):
"""
Initialisiert Logger mit Systemmetadaten und Defaultwerten.
Initializes the logger with system metadata and default values.
"""
self.name: str = FusionLogger.__name__
self.scope: str = ""
Expand All @@ -65,90 +64,88 @@ def __init__(self):
self.hostname: str = socket.gethostname()
self.pid: int = os.getpid()
self.tid: int = threading.current_thread().ident
self.log_files: set = set()

# Outer methods
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def debug(self, message: str, exception: Exception = None) -> None:
"""
Loggt eine Nachricht auf DEBUG-Level.
Logs a message at the DEBUG level.

Args:
message: Zu loggende Textnachricht
exception: Optionales Exception-Objekt (Standard: None)
message: The text message to log
exception: Optional exception object (default: None)
"""
self.__log(FusionLogLevel.DEBUG, message, exception)

def info(self, message: str, exception: Exception = None) -> None:
"""
Loggt eine Nachricht auf INFO-Level.
Logs a message at the INFO level.

Args:
message: Zu loggende Textnachricht
exception: Optionales Exception-Objekt (Standard: None)
message: The text message to log
exception: Optional exception object (default: None)
"""
self.__log(FusionLogLevel.INFO, message, exception)

def warning(self, message: str, exception: Exception = None) -> None:
"""
Loggt eine Nachricht auf WARNING-Level.
Logs a message at the WARNING level.

Args:
message: Zu loggende Textnachricht
exception: Optionales Exception-Objekt (Standard: None)
message: The text message to log
exception: Optional exception object (default: None)
"""
self.__log(FusionLogLevel.WARNING, message, exception)

def critical(self, message: str, exception: Exception = None) -> None:
"""
Loggt eine Nachricht auf CRITICAL-Level.
Logs a message at the CRITICAL level.

Args:
message: Zu loggende Textnachricht
exception: Optionales Exception-Objekt (Standard: None)
message: The text message to log
exception: Optional exception object (default: None)
"""
self.__log(FusionLogLevel.CRITICAL, message, exception)

def begin_scope(self, scope: str) -> None:
"""
Aktiviert einen neuen Logging-Kontextbereich.
Activates a new logging context scope.

Args:
scope: Name des neuen Kontextbereichs
scope: Name of the new scope
"""
self.scope = scope

def end_scope(self, scope: str) -> None:
"""
Beendet den aktuellen Logging-Kontextbereich.
Ends the current logging context scope.

Args:
scope: Name des zu schließenden Bereichs (Prüfung auf Konsistenz)
scope: Name of the scope to close (checks for consistency)
"""
if self.scope == scope:
self.scope = ""

def set_min_level(self, min_level: FusionLogLevel) -> None:
"""
Setzt die minimale Ausgabestufe für Logs.
Sets the minimum output level for logs.

Args:
min_level: Neue Mindeststufe als FusionLogLevel-Enum
min_level: New minimum level as a FusionLogLevel enum
"""
self.min_level = min_level

# Inner methods
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def __log(self, level: FusionLogLevel, message: str, exception: Exception):
"""
Interner Logging-Mechanismus (muss implementiert werden).
Internal logging mechanism (must be implemented).

Args:
level: Gewünschtes Log-Level
message: Zu loggende Nachricht
exception: Optionale Exception-Referenz

Raises:
NotImplementedError: Bei direkter Verwendung der Basisklasse
level: Desired log level
message: Message to log
exception: Optional exception reference
"""
if self.__is_enabled(level):
logging_record: FusionLogRecord = FusionLogRecord(
Expand All @@ -159,92 +156,109 @@ def __log(self, level: FusionLogLevel, message: str, exception: Exception):
hostname=self.hostname,
process_id=self.pid,
thread_id=self.tid,
exception=exception
exception=exception,
files=self.log_files
)
self.processor.process_record(logging_record)

def __is_enabled(self, level: FusionLogLevel) -> bool:
"""
Prüft, ob Logging für angegebenes Level aktiviert ist.
Checks if logging is enabled for the specified level.

Args:
level: Zu prüfendes Log-Level
level: Log level to check

Returns:
bool: True wenn Logging erlaubt, sonst False
bool: True if logging is allowed, False otherwise
"""
return level.value >= self.min_level.value


class FusionLoggerBuilder():
class FusionLoggerBuilder:
"""
Fluent Builder für die Konfiguration von fusion_logger-Instanzen.
Fluent builder for configuring fusion_logger instances.

Ermöglicht method chaining für einfache Logger-Erstellung.
Allows method chaining for easy logger creation.
"""

def __init__(self):
"""
Initialisiert Builder mit Standard-Loggerkonfiguration.
Initializes the builder with a standard logger configuration.
"""
self.__logger = FusionLogger()

def set_name(self, name: str):
"""
Setzt den Logger-Namen.
Sets the logger name.

Args:
name: Eindeutiger Identifikator für den Logger
name: Unique identifier for the logger

Returns:
FusionLoggerBuilder: Selbstreferenz für Method Chaining
FusionLoggerBuilder: Self-reference for method chaining
"""
self.__logger.name = name
return self

def set_min_level(self, level: FusionLogLevel):
"""
Konfiguriert die minimale Log-Stufe.
Configures the minimum log level.

Args:
level: Gewünschte Mindeststufe
level: Desired minimum level

Returns:
FusionLoggerBuilder: Selbstreferenz für Method Chaining
FusionLoggerBuilder: Self-reference for method chaining
"""
self.__logger.min_level = level
return self

def set_formatter(self, fusion_formatter: FusionLogFormatter):
"""
Setzt benutzerdefinierten Log-Formatter.
Sets a custom log formatter.

Args:
fusion_formatter: Formatter-Instanz
fusion_formatter: Formatter instance

Returns:
FusionLoggerBuilder: Selbstreferenz für Method Chaining
FusionLoggerBuilder: Self-reference for method chaining
"""
self.__logger.formatter = fusion_formatter
return self

def build(self):
def write_to_file(self, path: str):
"""
Erzeugt final konfigurierte Logger-Instanz.
Adds a file path for logging output.

Args:
path: File path to write logs to

Returns:
FusionLogger: Vollständig konfigurierter Logger
FusionLoggerBuilder: Self-reference for method chaining
"""
return self.__logger
self.__logger.log_files.add(path)
return self

def write_to_files(self, *args: str):
"""
Adds multiple file paths for logging output.

if __name__ == "__main__":
formatter = FusionLogFormatter("[{LEVEL}] {TIMESTAMP} [{NAME}] {MESSAGE}")
logger = (FusionLoggerBuilder()
.set_formatter(formatter)
.set_min_level(FusionLogLevel.DEBUG)
.build())
logger.debug("Hallo")
logger.info("Hallo")
logger.warning("Hallo")
logger.critical("Hallo")
Args:
*args: Variable number of file paths

Returns:
FusionLoggerBuilder: Self-reference for method chaining
"""
paths = list(args)
for path in paths:
self.__logger.log_files.add(path)
return self

def build(self):
"""
Creates a fully configured logger instance.

Returns:
FusionLogger: Fully configured logger
"""
return self.__logger
Loading