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 setup_logging(config: Dict[str, Any]) -> None: """ Process -v/--verbose, --logfile options """ # Log level verbosity = config['verbosity'] # Log to stderr log_handlers: List[logging.Handler] = [logging.StreamHandler(sys.stderr)] 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 = 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.setFormatter( Formatter('%(name)s - %(levelname)s - %(message)s')) log_handlers.append(handler) 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 = 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.setFormatter( Formatter('%(name)s - %(levelname)s - %(message)s')) log_handlers.append(handler) else: log_handlers.append( RotatingFileHandler( logfile, maxBytes=1024 * 1024, # 1Mb backupCount=10)) logging.basicConfig( level=logging.INFO if verbosity < 1 else logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=log_handlers) _set_loggers(verbosity) logger.info('Verbosity set to %s', verbosity)
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...")
import subprocess import psutil import time import logging import requests import json import threading from systemd.journal import JournaldLogHandler log = logging.getLogger('centry') log.addHandler(JournaldLogHandler()) log.setLevel(logging.INFO) class WatcherThread(threading.Thread): def __init__(self, config): threading.Thread.__init__(self) self.configure(config) if config["enable"] == True: self._running = True else: self._running = False def configure(self, config): self.minFreeSpace = config["minFreeSpace"] self.increaseStep = config["increaseStep"] self.checkInterval = config["checkInterval"] self.EC2volumeId = config["EC2VolumeId"] self.EC2rootDrive = config["EC2rootDrive"] self.EC2rootPart = config["EC2rootPart"] self.EC2rootPartNum = config["EC2rootPartNum"]
#!/usr/bin/env python 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()
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 create_logger(self): self.log = logging.getLogger('app_logger') self.log.propagate = False self.log.setLevel(logging.DEBUG) self.log.addHandler(JournaldLogHandler())
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()
from config.secrets import * from commands.basic import * from commands.admin import * #from commands.rp import * #from selma.selma_client import Client as SelmaClient from utils.checks import load_config from systemd.journal import JournaldLogHandler from utils.spiffyText import spiff import logging import traceback from datetime import datetime as dt logger = logging.getLogger('discord') # instantiate the JournaldLogHandler to hook into systemd journald_handler = JournaldLogHandler() logging.addLevelName(logging.DEBUG, 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'
#import syslog import datetime import json import select from kodijson import Kodi from libby.remote import udpRemote import paho.mqtt.client as mqtt #import the client1 import resources_rc import logging logger = logging.getLogger("FLURZENTRALE") try: from systemd.journal import JournaldLogHandler logger.addHandler(JournaldLogHandler()) logger.info("Logging to systemdi this time") except: fh = logging.FileHandler(path.expanduser("~/fz.log")) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) logger.setLevel(logging.INFO) logger.info("No systemd logger detected, logging to file instead") #logger.setLevel(logging.DEBUG) logger.setLevel(logging.INFO) garagn_tcp_addr = 'garagn' garagn_tcp_port = 80
# return lib.KeyPressCallback(key, duration) # 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
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)