def setup_logging(config: Dict[str, Any]) -> None: """ Process -v/--verbose, --logfile options """ # Log level verbosity = config['verbosity'] logging.root.addHandler(bufferHandler) logfile = config.get('logfile') if logfile: s = logfile.split(':') if s[0] == 'syslog': # Address can be either a string (socket filename) for Unix domain socket or # a tuple (hostname, port) for UDP socket. # Address can be omitted (i.e. simple 'syslog' used as the value of # config['logfilename']), which defaults to '/dev/log', applicable for most # of the systems. address = (s[1], int(s[2])) if len(s) > 2 else s[1] if len(s) > 1 else '/dev/log' handler_sl = get_existing_handlers(SysLogHandler) if handler_sl: logging.root.removeHandler(handler_sl) handler_sl = SysLogHandler(address=address) # No datetime field for logging into syslog, to allow syslog # to perform reduction of repeating messages if this is set in the # syslog config. The messages should be equal for this. handler_sl.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s')) logging.root.addHandler(handler_sl) elif s[0] == 'journald': try: from systemd.journal import JournaldLogHandler except ImportError: raise OperationalException("You need the systemd python package be installed in " "order to use logging to journald.") handler_jd = get_existing_handlers(JournaldLogHandler) if handler_jd: logging.root.removeHandler(handler_jd) handler_jd = JournaldLogHandler() # No datetime field for logging into journald, to allow syslog # to perform reduction of repeating messages if this is set in the # syslog config. The messages should be equal for this. handler_jd.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s')) logging.root.addHandler(handler_jd) else: handler_rf = get_existing_handlers(RotatingFileHandler) if handler_rf: logging.root.removeHandler(handler_rf) handler_rf = RotatingFileHandler(logfile, maxBytes=1024 * 1024 * 10, # 10Mb backupCount=10) handler_rf.setFormatter(Formatter(LOGFORMAT)) logging.root.addHandler(handler_rf) logging.root.setLevel(logging.INFO if verbosity < 1 else logging.DEBUG) _set_loggers(verbosity, config.get('api_server', {}).get('verbosity', 'info')) logger.info('Verbosity set to %s', verbosity)
def get_logger(name): logger = logging.getLogger(name) if platform == 'linux': from systemd.journal import JournaldLogHandler journald_handler = JournaldLogHandler() journald_handler.setFormatter( logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s')) logger.addHandler(journald_handler) else: logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger.setLevel(logging.INFO) return logger
def __init__(self): # Getting an instance of the logger object this module will use self.__logger = logging.getLogger(self.__class__.__name__) # Instantiating the JournaldLogHandler to hook into systemd journald_handler = JournaldLogHandler() # Setting a formatter to include the level name journald_handler.setFormatter( logging.Formatter('[%(levelname)s] %(message)s')) # Adding the journald handler to the current logger self.__logger.addHandler(journald_handler) # Setting the logging level self.__logger.setLevel(logging.INFO)
def getLogger(config: dict=None): isUseJournald = config.get("journald") handler = logging.StreamHandler() if isUseJournald: try: from systemd.journal import JournaldLogHandler handler = JournaldLogHandler() except: print("systemd not installed giveup using journald. Using StreamHandler stdout/stderr as fallback.") pass logger = logging.getLogger() formatter = logging.Formatter( '%(asctime)s - %(levelname)s %(filename)s(%(lineno)d) %(funcName)s(): \t %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(config.get('log_level')) return logger
def __init__(self): # Getting an instance of the logger object this module will use self.__logger = logging.getLogger(self.__class__.__name__) # Instantiating the JournaldLogHandler to hook into systemd journald_handler = JournaldLogHandler() # Setting a formatter to include the level name journald_handler.setFormatter( logging.Formatter('[%(levelname)s] %(message)s')) # Adding the journald handler to the current logger self.__logger.addHandler(journald_handler) # Setting the logging level self.__logger.setLevel(logging.INFO) # Setting global values related to the application # Getting current working directory util.settings.application_path = os.getcwd()
def setup_logger(logfile, loglevel=20): # INFO loglevel # Add a logger logger = logging.getLogger(LOGGER_NAME) # instantiate the JournaldLogHandler to hook into systemd journald_handler = JournaldLogHandler() # set a formatter to include the level name journald_handler.setFormatter( logging.Formatter('[%(levelname)s] %(message)s')) # instantiate the FileHandler file_handler = logging.FileHandler(logfile) file_handler.setFormatter( logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s')) # add the journald handler to the current logger logger.addHandler(journald_handler) logger.addHandler(file_handler) logger.setLevel(loglevel) logger.info("Started Agent Log")
def __init__(self): # Getting an instance of the logger object this module will use self.__logger = logging.getLogger(self.__class__.__name__) # Instantiating the JournaldLogHandler to hook into systemd journald_handler = JournaldLogHandler() # Setting a formatter to include the level name journald_handler.setFormatter( logging.Formatter('[%(levelname)s] %(message)s')) # Adding the journald handler to the current logger self.__logger.addHandler(journald_handler) # Setting the logging level self.__logger.setLevel(logging.INFO) # Setting global values related to the application self.__conf_file_path = '{application_path}/{conf_file}'.format( application_path=application_path, conf_file=CONF_FILE) self.__logger.info( "Configuration file should be located at {conf_file_path}".format( conf_file_path=self.__conf_file_path)) print( "Configuration file should be located at {conf_file_path}".format( conf_file_path=self.__conf_file_path)) self.__user_settings = [] # Reading configuration file (kayordomo.yaml) if os.path.exists(self.__conf_file_path): conf_file = open(self.__conf_file_path) self.__user_settings = yaml.load(conf_file, Loader=yaml.FullLoader) conf_file.close() else: self.__logger.info("Warning: There is no configuration file...") print("Warning: There is no configuration file...")
# command callback def command_callback(cmd): return lib.CommandCallback(cmd) def exitfunction(signum, frame): sys.exit() if __name__ == '__main__': signal.signal(signal.SIGTERM, exitfunction) logger = logging.getLogger("CECCOM") journald_handler = JournaldLogHandler() journald_handler.setFormatter( logging.Formatter('[%(levelname)s] %(message)s')) logger.addHandler(journald_handler) logger.setLevel(logging.DEBUG) # initialise libCEC cecqueue = queue.Queue() exception = False bosecomobj = serialcom.bosecom('/dev/ttyAMA0', 50, cecqueue, logger) lib = ceccom(cecqueue, bosecomobj, logger) lib.SetLogCallback(log_callback) # Somehow this function isn't working # lib.SetKeyPressCallback(key_press_callback) lib.SetCommandCallback(command_callback) lib.daemon = True bosecomobj.daemon = True lib.start() bosecomobj.start()
import argparse import logging import sys import time from pathlib import Path from datetime import datetime from systemd.journal import JournaldLogHandler from archive import Archive from cameras import CameraConfig, CameraList, Camera from imcommon import in_time_window, is_daylight logger = logging.getLogger(__name__) handler = JournaldLogHandler() fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(fmt) logger.addHandler(handler) logger.setLevel(logging.DEBUG) def cli(): ap = argparse.ArgumentParser() ap.add_argument('--config_file', type=str, required=True, help='path to a config file') ap.add_argument('--debug', action='store_true') return ap.parse_args() def main(args):
import logging import os from titus_isolate.config.constants import LOG_FMT_STRING log = logging.getLogger() log.setLevel(logging.INFO) if 'DISTRIB_ID' in os.environ and 'TITUS_TASK_ID' not in os.environ: from systemd.journal import JournaldLogHandler journald_handler = JournaldLogHandler() journald_handler.setFormatter(logging.Formatter(LOG_FMT_STRING)) log.addHandler(journald_handler)
def main(): """Run main function.""" run_setup_commands() FAPP.run(host='127.0.0.1', port=FLASK_PORT, debug=DEBUG) if __name__ == '__main__': # logging.basicConfig() LOG = logging.getLogger('allports-listening') PARSER = argparse.ArgumentParser() PARSER.add_argument( '-l', '--logger', help='type of logger', choices=['stdout', 'systemd'], default='stdout', type=str, ) ARGS = PARSER.parse_args() if ARGS.logger == 'systemd': HANDLER = JournaldLogHandler() else: HANDLER = logging.StreamHandler(sys.stdout) HANDLER.setFormatter(logging.Formatter('[%(levelname)s] %(message)s')) LOG.addHandler(HANDLER) LOG.setLevel(logging.INFO) logging.getLogger('werkzeug').setLevel(logging.WARN) main()
from signal import (signal, SIGINT, SIGTERM, SIGABRT, SIGUSR1, SIGUSR2) from time import sleep from telegram.ext import (Updater, CommandHandler, Filters) # Enable logging logger = logging.getLogger(__file__.replace('.py', '')) logging.basicConfig(format='%(asctime)s %(name)s - %(levelname)s: %(message)s', level=logging.INFO) logging.propagate = 0 log_fmt = logging.Formatter('%(levelname)s: %(message)s') log_ch = JournalHandler(identifier='OpenVPNCertBot') log_ch.setFormatter(log_fmt) logger.addHandler(log_ch) class FilesContainer: def __init__(self): self.lock = threading.Lock() self.users_list = [] self.users = {} self.certs = [] self.awaiting = {} def load_all(self): self.lock.acquire()
spiff(logging.getLevelName(logging.DEBUG), 'yellow')) logging.addLevelName(logging.INFO, spiff(logging.getLevelName(logging.INFO), 'cyan')) logging.addLevelName( logging.WARNING, spiff(logging.getLevelName(logging.WARNING), 'yellow', 'b')) logging.addLevelName(logging.ERROR, spiff(logging.getLevelName(logging.ERROR), 'red')) logging.addLevelName(logging.CRITICAL, spiff(logging.getLevelName(logging.CRITICAL), 'red', 'b')) logging_format = '%(levelname)s %(module)s::%(funcName)s():%(lineno)d: ' logging_format += '%(message)s' color_formatter = logging.Formatter(logging_format) journald_handler.setFormatter(color_formatter) logger.addHandler(journald_handler) logger.setLevel(logging.DEBUG) class SirCharles(Bot): async def on_ready(self): logger.info('Connected!') logger.info('Username: {0.name}\nID: {0.id}'.format(self.user)) channel = self.get_channel(BOT_DEBUG_CHANNEL) self.mongo_client = MongoClient() self.commands_db = self.mongo_client['commands'] self.com = self.commands_db.com await channel.send("I'm alive!") async def on_member_join(self, member):
os.close(0) # Close stdout os.close(1) # Close stderr os.close(2) # Logger configuration log_level = 0 if args.verbose: log_level = logging.DEBUG elif args.quiet: log_level = logging.ERROR else: log_level = logging.INFO logger = logging.getLogger(__name__) journald_handler = JournaldLogHandler() journald_handler.setFormatter( logging.Formatter("[%(levelname)s](%(asctime)s): %(message)s")) logger.addHandler(journald_handler) logger.setLevel(log_level) logger.debug("##-> DC/OS Journal IP: %s", args.dcos_journal_ip) logger.debug("##-> DC/OS Journal Port: %d", args.dcos_journal_port) logger.debug("##-> Rsyslog IP: %s", args.rsyslog_ip) logger.debug("##-> Rsyslog Port: %d", args.rsyslog_port) # Run Daemon run(args.dcos_journal_ip, args.dcos_journal_port, args.rsyslog_ip, args.rsyslog_port, args.buffer_read_size)