Skip to content

Instantly share code, notes, and snippets.

@junetech
Created November 7, 2024 06:48
Show Gist options
  • Save junetech/34f8fed34ac9a0e646ba3907c56e79fb to your computer and use it in GitHub Desktop.
Save junetech/34f8fed34ac9a0e646ba3907c56e79fb to your computer and use it in GitHub Desktop.
SFlogger
r"""
Copyright (c) 2024 MSO Lab.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
""" # noqa: E501 W605
import logging
from datetime import datetime
LOG_FILENAME = "mylog.log"
LOG_ENCODING = "utf-8"
FILE_LOGGER_NAME = "SF_file"
STREAM_LOGGER_NAME = "SF_stream"
class SFLogger(object):
def __init__(
self, log_filename: str = LOG_FILENAME, log_encoding: str = LOG_ENCODING
):
self.start_d = datetime.now()
self.last_d = self.start_d
self.flogger = logging.getLogger(FILE_LOGGER_NAME)
self.flogger.setLevel(logging.INFO)
fhandler = logging.FileHandler(log_filename, encoding=log_encoding)
self.flogger.addHandler(fhandler)
self.flogger.propagate = False
self.slogger = logging.getLogger(STREAM_LOGGER_NAME)
self.slogger.setLevel(logging.INFO)
shandler = logging.StreamHandler()
self.slogger.addHandler(shandler)
self.slogger.propagate = False
self.log_with_time_as_info(f"{self.__class__.__name__} initialized")
def __del__(self):
# release logger handlers
self.flogger.handlers.clear()
self.slogger.handlers.clear()
def log_as_info(self, msg: str):
self.flogger.info(msg)
self.slogger.info(msg)
def log_with_time_as_info(self, msg: str):
this_d = datetime.now()
msg_with_time = f"{msg} @ {this_d}"[:-3] + f"; took {this_d - self.last_d}"[:-3]
self.log_as_info(msg_with_time)
self.last_d = this_d
def log_with_running_time_as_info(self, msg: str):
this_d = datetime.now()
msg_with_time = (
f"{msg} @ {this_d}"[:-3] + f"; took {this_d - self.start_d}"[:-3]
)
self.log_as_info(msg_with_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment