Skip to content

Commit

Permalink
Add custom formatter ability
Browse files Browse the repository at this point in the history
  • Loading branch information
csm10495 committed Jul 7, 2021
1 parent 060d086 commit 11f3175
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
32 changes: 28 additions & 4 deletions csmlog/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'''
This file is part of csmlog. Python logger setup... the way I like it.
MIT License (2020) - Charles Machalow
MIT License (2021) - Charles Machalow
'''

import logging
Expand All @@ -16,17 +16,22 @@
from csmlog.udp_handler import UdpHandler
from csmlog.udp_handler_receiver import UdpHandlerReceiver

__version__ = '0.23.0'
__version__ = '0.24.0'

DEFAULT_LOG_FORMAT = '%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s'

class CSMLogger(object):
'''
object to wrap logging logic
'''
def __init__(self, appName, clearLogs=False, udpLogging=True, googleSheetShareEmail=None):
def __init__(self, appName, clearLogs=False, udpLogging=True, googleSheetShareEmail=None, formatter=None):
self.appName = appName
self.udpLogging = udpLogging
self.googleSheetShareEmail = googleSheetShareEmail
self._loggers = []

# sets self._formatter
self.setFormatter(formatter)

if clearLogs:
self.clearLogs()
Expand Down Expand Up @@ -107,7 +112,7 @@ def rotate(self, source, dest):
return logger

def getFormatter(self):
return logging.Formatter('%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s')
return self._formatter

def getDefaultSaveDirectory(self):
return self.getDefaultSaveDirectoryWithName(self.appName)
Expand Down Expand Up @@ -136,6 +141,19 @@ def disableConsoleLogging(self):
self.parentLogger.removeHandler(self.consoleLoggingStream)
self.consoleLoggingStream = None

def setFormatter(self, formatter=None):
if formatter is None:
formatter = logging.Formatter(DEFAULT_LOG_FORMAT)

if isinstance(formatter, str):
formatter = logging.Formatter(formatter)

self._formatter = formatter

for logger in self._loggers:
for handler in logger.handlers:
handler.setFormatter(formatter)

@classmethod
def getDefaultSaveDirectoryWithName(cls, appName):
if os.name == 'nt':
Expand Down Expand Up @@ -215,6 +233,12 @@ def disableConsoleLogging(self, *args, **kwargs):

return self._activeCsmLogger.disableConsoleLogging(*args, **kwargs)

def setFormatter(self, formatter=None):
if not self._activeCsmLogger:
raise RuntimeError("(csmlog) setup() must be called first!")

return self._activeCsmLogger.setFormatter(formatter)

def setup(self, appName, clearLogs=False, udpLogging=True, googleSheetShareEmail=None):
''' must be called to setup the logger. Passes args to CSMLogger's constructor '''

Expand Down
23 changes: 23 additions & 0 deletions csmlog/tests/test_csmlog.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import io
import logging
import os
import subprocess
import sys
Expand Down Expand Up @@ -188,3 +189,25 @@ def test_added_attrs_on_logger(csmlog):
assert not pathlib.Path(tmp.logFile).is_file()
tmp.info("hi")
assert pathlib.Path(tmp.logFile).is_file()


def test_formatter_setting(csmlog):
logger = csmlog.getLogger('log')
logger.debug("helloworld")
assert 'DEBUG' in pathlib.Path(logger.logFile).read_text()

csmlog.setFormatter('%(created)f')
logger.debug("helloworld")
assert 'helloworld' not in pathlib.Path(logger.logFile).read_text().splitlines()[-1]

csmlog.setFormatter(logging.Formatter('%(created)f'))
logger.debug("helloworld")
assert 'helloworld' not in pathlib.Path(logger.logFile).read_text().splitlines()[-1]

logger2 = csmlog.getLogger('log2')
logger2.debug("helloworld")
assert 'helloworld' not in pathlib.Path(logger2.logFile).read_text().splitlines()[-1]

csmlog.setFormatter()
logger.debug("helloworld")
assert 'helloworld' in pathlib.Path(logger.logFile).read_text().splitlines()[-1]

0 comments on commit 11f3175

Please sign in to comment.