Skip to content

Instantly share code, notes, and snippets.

@meta-ks
Created May 17, 2023 03:35
Show Gist options
  • Save meta-ks/217ce41fc215e69a630db576bbbd23bc to your computer and use it in GitHub Desktop.
Save meta-ks/217ce41fc215e69a630db576bbbd23bc to your computer and use it in GitHub Desktop.
The `FileLogger` class is a custom logging class for Python that extends the functionality of the built-in `logging.Logger` class. It provides the ability to log messages ONLY to a file and optionally to the console, with customizable file name, mode, log level, and formatter.
import logging
# Create a custom logger class
class FileLogger(logging.Logger):
def __init__(self, name, filename, mode='a', level=logging.INFO, fformatter=None, log_to_console=False, sformatter=None):
super().__init__(name, level)
# Create a custom file handler
self.file_handler = logging.FileHandler(filename=filename, mode=mode)
# Set the formatter for the file handler
if fformatter is not None:
self.file_handler.setFormatter(fformatter)
# Add the file handler to the logger
self.addHandler(self.file_handler)
if log_to_console:
# Create a console handler
self.console_handler = logging.StreamHandler() # Prints to the console
# Set the formatter for the console handler
if not sformatter:
sformatter = fformatter
self.console_handler.setFormatter(sformatter)
# Add the console handler to the logger
self.addHandler(self.console_handler)
def fdebug(self, msg, pre_msg=''):
if pre_msg:
print(pre_msg)
self.debug(msg)
def finfo(self, msg):
self.info(msg)
def fwarn(self, msg):
self.warning(msg)
def ferror(self, msg):
self.error(msg)
def fcritical(self, msg):
self.critical(msg)
# Test the logging
if __name__ == '__main__':
s_log_level = logging.CRITICAL
file_log_level = logging.WARN
log_format = "[%(asctime)s.%(msecs)03d] %(message)s"
log_fp = f'tmp.log'
logging.basicConfig(format=log_format, level=s_log_level, datefmt="%H:%M:%S")
# Create an instance of the custom logger
formatter = logging.Formatter(log_format, "%H:%M:%S")
fLogger = FileLogger(__name__, log_fp, mode='a', level=file_log_level, fformatter=formatter)
fLogger.fdebug("This will be logged to file with DEBUG level")
fLogger.finfo("This will be logged to file with INFO level")
fLogger.fwarn("This will be logged to file with WARNING level")
fLogger.ferror("This will be logged to file with ERROR level")
fLogger.fcritical("This will be logged to file with CRITICAL level")
logging.debug("This Debug will be logged to console")
logging.info("This info will be logged to console")
logging.warning("This warning also be logged to console")
logging.critical("This critical also be logged to console")
@meta-ks
Copy link
Author

meta-ks commented May 17, 2023

Note: Logging in Python can be complex, and the default logging module has some limitations.
It doesn't provide a straightforward way to log messages exclusively to a file without logging them to the console.
The FileLogger class presented here extends the built-in logging functionality to overcome this limitation,
allowing you to log messages to both a file and the console, or exclusively to a file if desired.
It provides a simple and customizable solution for file-based logging in Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment