class JournalLoggingPlugin(PithosPlugin): preference = 'journald-logging' description = _('Store logs with the journald service') _logging_changed_handler = None def on_prepare(self): try: from systemd.journal import JournalHandler self._journal = JournalHandler( SYSLOG_IDENTIFIER='io.github.Pithos') self._journal.setFormatter(logging.Formatter()) self._logger = logging.getLogger() self.preferences_dialog = LoggingPluginPrefsDialog( self.window, self.settings) except ImportError: self.prepare_complete(error=_('Systemd Python module not found')) else: self.prepare_complete() def on_enable(self): self._on_logging_changed(None, self.settings['data'] or 'verbose') self._logger.addHandler(self._journal) self._logging_changed_handler = self.preferences_dialog.connect( 'logging-changed', self._on_logging_changed) def _on_logging_changed(self, prefs_dialog, level): self.settings['data'] = level self._journal.setLevel(LOG_LEVELS[level]) logging.info('setting journald logging level to: {}'.format(level)) def on_disable(self): if self._logging_changed_handler: self.preferences_dialog.disconnect(self._logging_changed_handler) self._logger.removeHandler(self._journal)
def do_command_line(self, command_line): options = command_line.get_options_dict() # First, get rid of existing logging handlers due to call in header as per # http://stackoverflow.com/questions/1943747/python-logging-before-you-run-logging-basicconfig logging.root.handlers = [] # Show the version on local instance and exit if options.contains('version'): # Broken bindings... type(command_line).do_print_literal( command_line, "Pithos {}\n".format(self.version)) return 0 handlers = [] try: from systemd.journal import JournalHandler journal = JournalHandler( SYSLOG_IDENTIFIER=self.props.application_id) # We can be more verbose with the journal and filter it later # and don't need fancy formatting as its part of the structure journal.setLevel(logging.INFO) journal.setFormatter(logging.Formatter()) handlers.append(journal) except ImportError: pass # Set the logging level to show debug messages if options.contains('debug'): log_level = logging.DEBUG elif options.contains('verbose'): log_level = logging.INFO else: log_level = logging.WARN stream = logging.StreamHandler() stream.setLevel(log_level) stream.setFormatter( logging.Formatter( fmt= '%(levelname)s - %(module)s:%(funcName)s:%(lineno)d - %(message)s' )) handlers.append(stream) logging.basicConfig(level=logging.NOTSET, handlers=handlers) self.test_mode = options.lookup_value('test') self.do_activate() return 0
def add_stderr_journal_handler(logger=logging.root, level=logging.INFO): if logger.getEffectiveLevel() > level: logger.setLevel(level) try: from systemd.journal import JournalHandler from idb import __version__ h = JournalHandler( SYSLOG_IDENTIFIER=os.path.basename(sys.argv[0]), VERSION=__version__) except: h = logging.StreamHandler() h.setFormatter(logging.Formatter(TIMELESS_FORMAT)) h.setLevel(level) logger.addHandler(h) return h
def do_command_line(self, command_line): options = command_line.get_options_dict() # First, get rid of existing logging handlers due to call in header as per # http://stackoverflow.com/questions/1943747/python-logging-before-you-run-logging-basicconfig logging.root.handlers = [] # Show the version on local instance and exit if options.contains('version'): # Broken bindings... type(command_line).do_print_literal(command_line, "Pithos {}\n".format(self.version)) return 0 handlers = [] try: from systemd.journal import JournalHandler journal = JournalHandler(SYSLOG_IDENTIFIER=self.props.application_id) # We can be more verbose with the journal and filter it later # and don't need fancy formatting as its part of the structure journal.setLevel(logging.INFO) journal.setFormatter(logging.Formatter()) handlers.append(journal) except ImportError: pass # Set the logging level to show debug messages if options.contains('debug'): log_level = logging.DEBUG elif options.contains('verbose'): log_level = logging.INFO else: log_level = logging.WARN stream = logging.StreamHandler() stream.setLevel(log_level) stream.setFormatter(logging.Formatter(fmt='%(levelname)s - %(module)s:%(funcName)s:%(lineno)d - %(message)s')) handlers.append(stream) logging.basicConfig(level=logging.NOTSET, handlers=handlers) self.test_mode = options.lookup_value('test') self.do_activate() return 0
def get_main_logger(): """ Returns a main logger object for use by the Gtk.Application. Should not be used by normal applications. Returns: :logging.Logger: The logger for the main application """ # Use verbose debug logging for now. console_loglevel = VERBOSITY_LEVELS[2] file_loglevel = VERBOSITY_LEVELS[2] console_fmt = logging.Formatter('%(name)s: %(levelname)s %(message)s') file_fmt = logging.Formatter( '%(asctime)s - %(name)s: %(levelname)s %(message)s') log = logging.getLogger('toggledarkly') console_log = logging.StreamHandler() console_log.setFormatter(console_fmt) console_log.setLevel(console_loglevel) log.addHandler(console_log) file_log = handlers.RotatingFileHandler(LOG_FILE_PATH, maxBytes=(1048576 * 5), backupCount=5) file_log.setFormatter(file_fmt) file_log.setLevel(file_loglevel) log.addHandler(file_log) if SYSTEMD_SUPPORT: journald_log = JournalHandler() journald_log.setLevel(file_loglevel) journald_log.setFormatter(console_fmt) log.addHandler(journald_log) log.setLevel(VERBOSITY_LEVELS[2]) return log
def main(self, args): """ Do the thing """ log_file_path = '/var/log/kernelstub.log' if args.log_file: log_file_path = args.log_file verbosity = 0 if args.verbosity: verbosity = args.verbosity if verbosity > 2: verbosity = 2 if args.print_config: verbosity = 1 level = { 0 : logging.WARNING, 1 : logging.INFO, 2 : logging.DEBUG, } console_level = level[verbosity] file_level = level[2] stream_fmt = logging.Formatter( '%(name)-21s: %(levelname)-8s %(message)s') file_fmt = logging.Formatter( '%(asctime)s - %(name)-21s: %(levelname)-8s %(message)s') log = logging.getLogger('kernelstub') console_log = logging.StreamHandler() console_log.setFormatter(stream_fmt) console_log.setLevel(console_level) file_log = handlers.RotatingFileHandler( log_file_path, maxBytes=(1048576*5), backupCount=5) file_log.setFormatter(file_fmt) file_log.setLevel(file_level) log.addHandler(console_log) log.addHandler(file_log) if SYSTEMD_SUPPORT: journald_log = JournalHandler() journald_log.setLevel(file_level) journald_log.setFormatter(stream_fmt) log.addHandler(journald_log) log.setLevel(logging.DEBUG) # Figure out our command line options. log.debug('Got command line options: %s', args) if args.dry_run: log.warning( 'DEPRECATED!\n\n' 'The simulate or dry-run option has been removed from ' 'kernelstub and no longer functions. This will be removed in a ' 'future version. Since you likely intend no action, we will now ' 'exit.' ) exit() config = Config.Config() configuration = config.config['user'] if args.esp_path: configuration['esp_path'] = args.esp_path root_path = "/" if args.root_path: root_path = args.root_path opsys = Opsys.OS() if args.kernel_path: log.debug('Manual kernel path:\n %s', args.kernel_path) opsys.kernel_path = args.kernel_path else: opsys.kernel_path = os.path.join(root_path, opsys.kernel_name) if args.initrd_path: log.debug('Manual initrd path:\n %s', args.initrd_path) opsys.initrd_path = args.initrd_path else: opsys.initrd_path = os.path.join(root_path, opsys.initrd_name) if not os.path.exists(opsys.kernel_path): log.exception( 'Can\'t find the kernel image! \n\n Please use the ' '--kernel-path option to specify the path to the kernel image' ) exit(0) if not os.path.exists(opsys.initrd_path): log.exception( 'Can\'t find the initrd image! \n\n Please use the ' '--initrd-path option to specify the path to the initrd image' ) exit(0) # Check for kernel parameters. Without them, stop and fail if args.k_options: configuration['kernel_options'] = config.parse_options(args.k_options.split()) else: try: configuration['kernel_options'] except KeyError: error = ( 'cmdline was "InvalidConfig"\n\n Could not find any valid ' 'configuration. This probably means that the configuration ' 'file is corrupt. Either remove it to regenerate it from ' 'default or fix the existing one.' ) log.exception(error) raise CmdLineError("No Kernel Parameters found") exit(168) log.debug(config.print_config()) if args.preserve_live and configuration['live_mode']: configuration['live_mode'] = True log.warning( 'Live mode is enabled!\n' 'Kernelstub is running in live environment mode. This usually ' 'means that you are running a live disk, and kernelstub should ' 'not run. We are thus exiting with 0.\n' 'If you are not running a live disk, please run ' '`sudo kernelstub` to disable live mode.' ) exit(0) configuration['live_mode'] = False if args.setup_loader: configuration['setup_loader'] = True if args.off_loader: configuration['setup_loader'] = False if args.install_stub: configuration['manage_mode'] = False if args.manage_mode: configuration['manage_mode'] = True log.debug('Checking configuration integrity...') try: kernel_opts = configuration['kernel_options'] esp_path = configuration['esp_path'] setup_loader = configuration['setup_loader'] manage_mode = configuration['manage_mode'] force = configuration['force_update'] live_mode = configuration['live_mode'] except KeyError: log.exception( 'Malformed configuration! \n' 'The configuration we got is bad, and we can\'t continue. ' 'Please check the config files and make sure they are correct. ' 'If you can\'t figure it out, then deleting them should fix ' 'the errors and cause kernelstub to regenerate them from ' 'Default. \n\n You can use "-vv" to get the configuration used.' ) log.debug('Configuration we got: \n\n%s', config.print_config()) exit(169) if args.add_options: add_opts = args.add_options.split(" ") add_opts = config.parse_options(add_opts) for opt in add_opts: if opt not in kernel_opts: kernel_opts.append(opt) configuration['kernel_options'] = kernel_opts if args.remove_options: rem_opts = args.remove_options.split(" ") rem_opts = config.parse_options(rem_opts) kernel_opts = list(set(kernel_opts) - set(rem_opts)) configuration['kernel_options'] = kernel_opts if args.force_update: force = True if configuration['force_update'] is True: force = True log.debug('Structing objects') drive = Drive.Drive(root_path=root_path, esp_path=esp_path) nvram = Nvram.NVRAM(opsys.name, opsys.version) installer = Installer.Installer(nvram, opsys, drive) # Log some helpful information, to file and optionally console data_system = { 'Root:': drive.root_fs, 'ESP:': drive.esp_fs, 'Kernel Path:': opsys.kernel_path, 'Initrd Path:': opsys.initrd_path, 'Boot Options:': " ".join(kernel_opts), } data_debug = { 'OS:': "{} {}".format(opsys.name_pretty, opsys.version), 'ESP Partition #:': drive.esp_num, 'NVRAM entry #:': nvram.os_entry_index, 'Boot Variable #:': nvram.order_num, 'Root FS UUID:': drive.root_uuid, } data_config = { 'Kernel Options:': " ".join(kernel_opts), 'ESP Path:': esp_path, 'Install loader config:': setup_loader, 'Management Mode:': manage_mode, 'Force Overwrite:': str(force), 'Live Disk Mode:': live_mode, 'Config revision:': configuration['config_rev'] } if args.print_config: log.info( 'System information:\n\n%s', self.mktable(data_system, 22) ) log.debug( 'Debug information:\n\n%s', self.mktable(data_debug, 22) ) log.info( 'Active configuration details:\n\n%s', self.mktable(data_config, 22) ) exit(0) log.info( 'System information:\n\n%s', self.mktable(data_system, 16) ) log.debug( 'Debug information:\n\n%s', self.mktable(data_debug, 16) ) log.debug( 'Active configuration:\n\n%s', self.mktable(data_config, 22) ) if args.print_config: log.info( 'Active configuration details:\n\n%s', self.mktable(data_config, 22) ) exit(0) log.debug('Setting up boot...') kopts = 'root=UUID={uuid} ro {options}'.format( uuid=drive.root_uuid, options=" ".join(kernel_opts) ) log.debug('kopts: %s', kopts) installer.setup_kernel( kopts, setup_loader=setup_loader, overwrite=force) try: installer.backup_old( kopts, setup_loader=setup_loader) except Exception as e_e: log.debug( 'Couldn\'t back up old kernel. \nThis might just mean you ' 'don\'t have an older kernel installed. If you do, try with -vv' ' to see debugging information' ) log.debug(e_e) installer.copy_cmdline() if not manage_mode: installer.setup_stub(kopts) log.debug('Saving configuration to file') config.config['user'] = configuration config.save_config() log.debug('Setup complete!\n\n') return 0
def main(self, args): # Do the thing log_file_path = '/var/log/kernelstub.log' if args.log_file: log_file_path = args.log_file verbosity = 0 if args.verbosity: verbosity = args.verbosity if verbosity > 2: verbosity = 2 if args.print_config: verbosity = 1 level = { 0 : logging.WARNING, 1 : logging.INFO, 2 : logging.DEBUG, } console_level = level[verbosity] file_level = level[2] stream_fmt = logging.Formatter( '%(name)-21s: %(levelname)-8s %(message)s') file_fmt = logging.Formatter( '%(asctime)s - %(name)-21s: %(levelname)-8s %(message)s') log = logging.getLogger('kernelstub') console_log = logging.StreamHandler() console_log.setFormatter(stream_fmt) console_log.setLevel(console_level) file_log = handlers.RotatingFileHandler( log_file_path, maxBytes=(1048576*5), backupCount=5) file_log.setFormatter(file_fmt) file_log.setLevel(file_level) log.addHandler(console_log) log.addHandler(file_log) if systemd_support: journald_log = JournalHandler() journald_log.setLevel(file_level) journald_log.setFormatter(stream_fmt) log.addHandler(journald_log) log.setLevel(logging.DEBUG) log.debug('Got command line options: %s' % args) # Figure out runtime options no_run = False if args.dry_run: no_run = True config = Config.Config() configuration = config.config['user'] if args.esp_path: configuration['esp_path'] = args.esp_path root_path = "/" if args.root_path: root_path = args.root_path opsys = Opsys.OS() if args.kernel_path: log.debug( 'Manually specified kernel path:\n ' + ' %s' % args.kernel_path) opsys.kernel_path = args.kernel_path else: opsys.kernel_path = os.path.join(root_path, opsys.kernel_name) if args.initrd_path: log.debug( 'Manually specified initrd path:\n ' + ' %s' % args.initrd_path) opsys.initrd_path = args.initrd_path else: opsys.initrd_path = os.path.join(root_path, opsys.initrd_name) if not os.path.exists(opsys.kernel_path): log.exception('Can\'t find the kernel image! \n\n' 'Please use the --kernel-path option to specify ' 'the path to the kernel image') exit(0) if not os.path.exists(opsys.initrd_path): log.exception('Can\'t find the initrd image! \n\n' 'Please use the --initrd-path option to specify ' 'the path to the initrd image') exit(0) # Check for kernel parameters. Without them, stop and fail if args.k_options: configuration['kernel_options'] = self.parse_options(args.k_options.split()) else: try: configuration['kernel_options'] except KeyError: error = ("cmdline was 'InvalidConfig'\n\n" "Could not find any valid configuration. This " "probably means that the configuration file is " "corrupt. Either remove it to regenerate it from" "default or fix the existing one.") log.exception(error) raise CmdLineError("No Kernel Parameters found") exit(168) log.debug(config.print_config()) if args.preserve_live and configuration['live_mode']: configuration['live_mode'] = True log.warning( 'Live mode is enabled!\n' 'Kernelstub is running in live environment mode. This usually ' 'means that you are running a live disk, and kernelstub should ' 'not run. We are thus exiting with 0.\n' 'If you are not running a live disk, please run ' '`sudo kernelstub` to disable live mode.' ) exit(0) configuration['live_mode'] = False if args.setup_loader: configuration['setup_loader'] = True if args.off_loader: configuration['setup_loader'] = False if args.install_stub: configuration['manage_mode'] = False if args.manage_mode: configuration['manage_mode'] = True log.debug('Checking configuration integrity...') try: kernel_opts = configuration['kernel_options'] esp_path = configuration['esp_path'] setup_loader = configuration['setup_loader'] manage_mode = configuration['manage_mode'] force = configuration['force_update'] except KeyError: log.exception( 'Malformed configuration! \n' 'The configuration we got is bad, and we can\'nt continue. ' 'Please check the config files and make sure they are correct. ' 'If you can\'t figure it out, then deleting them should fix ' 'the errors and cause kernelstub to regenerate them from ' 'Default. \n\n You can use "-vv" to get the configuration used.') log.debug('Configuration we got: \n\n%s' % config.print_config()) exit(169) if args.add_options: add_opts = args.add_options.split(" ") add_opts = config.parse_options(add_opts) for opt in add_opts: if opt not in kernel_opts: kernel_opts.append(opt) configuration['kernel_options'] = kernel_opts if args.remove_options: rem_opts = args.remove_options.split(" ") rem_opts = config.parse_options(rem_opts) kernel_opts = list(set(kernel_opts) - set(rem_opts)) configuration['kernel_options'] = kernel_opts if args.force_update: force = True if configuration['force_update'] == True: force = True log.debug('Structing objects') drive = Drive.Drive(root_path=root_path, esp_path=esp_path) nvram = Nvram.NVRAM(opsys.name, opsys.version) installer = Installer.Installer(nvram, opsys, drive) # Log some helpful information, to file and optionally console info = ( ' OS:..................%s %s\n' %(opsys.name_pretty,opsys.version) + ' Root partition:......%s\n' % drive.root_fs + ' Root FS UUID:........%s\n' % drive.root_uuid + ' ESP Path:............%s\n' % esp_path + ' ESP Partition:.......%s\n' % drive.esp_fs + ' ESP Partition #:.....%s\n' % drive.esp_num + ' NVRAM entry #:.......%s\n' % nvram.os_entry_index + ' Boot Variable #:.....%s\n' % nvram.order_num + ' Kernel Boot Options:.%s\n' % " ".join(kernel_opts) + ' Kernel Image Path:...%s\n' % opsys.kernel_path + ' Initrd Image Path:...%s\n' % opsys.initrd_path + ' Force-overwrite:.....%s\n' % str(force)) log.info('System information: \n\n%s' % info) if args.print_config: all_config = ( ' ESP Location:..................%s\n' % configuration['esp_path'] + ' Management Mode:...............%s\n' % configuration['manage_mode'] + ' Install Loader configuration:..%s\n' % configuration['setup_loader'] + ' Configuration version:.........%s\n' % configuration['config_rev']) log.info('Configuration details: \n\n%s' % all_config) exit(0) log.debug('Setting up boot...') kopts = 'root=UUID=%s ro %s' % (drive.root_uuid, " ".join(kernel_opts)) log.debug('kopts: %s' % kopts) installer.setup_kernel( kopts, setup_loader=setup_loader, overwrite=force, simulate=no_run) try: installer.backup_old( kopts, setup_loader=setup_loader, simulate=no_run) except Exception as e: log.debug('Couldn\'t back up old kernel. \nThis might just mean ' + 'You don\'t have an old kernel installed. If you do, try ' + 'with -vv to see debuging information') log.debug(e) installer.copy_cmdline(simulate=no_run) if not manage_mode: installer.setup_stub(kopts, simulate=no_run) log.debug('Saving configuration to file') config.config['user'] = configuration config.save_config() log.debug('Setup complete!\n\n') return 0
class LogManager: def __init__(self): self.root = None self._file_formatter = None self._syslog_formatter = None self._console_formatter = None self._log_handler = None self._console_handler = None def init(self, log_level): self._file_formatter = logging.Formatter( "{asctime} [{name:<15.15}] [{levelname:<8.8}]: {message}", style="{") self._syslog_formatter = logging.Formatter( "[{name:>15.15}] [{levelname:<8.8}]: {message}", style="{") self._console_formatter = ColoredFormatter( "{log_color} * {reset}{message}", style="{", log_colors={ 'DEBUG': 'bold_cyan', 'INFO': 'bold_blue', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red' }) if HAS_SYSTEMD: self._log_handler = JournalHandler( SYSLOG_IDENTIFIER="clover-config") self._log_handler.setFormatter(self._syslog_formatter) else: log_path = os.path.join(os.path.expanduser("~"), ".local", "share", "clover-config") if not os.path.exists(log_path): os.makedirs(log_path) log_file = os.path.join(log_path, "clover-config.log") self._log_handler = logging.handlers.RotatingFileHandler( log_file, # 1MB size and 10 files maxBytes=1048576, backupCount=9) self._log_handler.setFormatter(self._file_formatter) self._log_handler.setLevel(logging.INFO) self._console_handler = logging.StreamHandler() self._console_handler.setFormatter(self._console_formatter) self.set_log_level(log_level) self.root = logging.getLogger() self.root.name = "clover-config" self.root.setLevel(logging.DEBUG) self.root.addHandler(self._log_handler) self.root.addHandler(self._console_handler) if HAS_SYSTEMD: self.root.debug("Using journald logging system...") else: self.root.debug("Logging to `{}`".format(log_file)) def __getattr__(self, name): return logging.getLogger(name) def die(self, code, message="An error occured during the execution of the current action" ): self.root.error("%s - aborting...", message) self.root.debug("Exiting with exit code %d", code) sys.exit(code.value) def set_log_level(self, log_level): log_levels = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR } level = log_levels[log_level] self._console_handler.setLevel(level)
import logging from systemd.journal import JournalHandler logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = JournalHandler() handler.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler)
'%(asctime)s - %(name)-21s: %(levelname)-8s %(message)s') log = logging.getLogger('pyflatpak') console_log = logging.StreamHandler() console_log.setFormatter(stream_fmt) console_log.setLevel(console_level) file_log = handlers.RotatingFileHandler(log_file_path, maxBytes=(1048576 * 5), backupCount=5) file_log.setFormatter(file_fmt) file_log.setLevel(file_level) log.addHandler(console_log) #log.addHandler(file_log) if SYSTEMD_SUPPORT: journald_log = JournalHandler() journald_log.setLevel(file_level) journald_log.setFormatter(stream_fmt) log.addHandler(journald_log) log.setLevel(logging.DEBUG) remotes = Remotes.Remotes() def validate(url): valid_fp_url = url.endswith('.flatpakrepo') return valid_fp_url
class JournalLoggingPlugin(PithosPlugin): preference = 'journald-logging' description = _('Store logs with the journald service') _logging_changed_handler = None def on_prepare(self): try: from systemd.journal import JournalHandler self._journal = JournalHandler(SYSLOG_IDENTIFIER='io.github.Pithos') self._journal.setFormatter(logging.Formatter()) self._logger = logging.getLogger() self.preferences_dialog = LoggingPluginPrefsDialog(self.window, self.settings) except ImportError: self.prepare_complete(error=_('Systemd Python module not found')) else: self.prepare_complete() def on_enable(self): self._on_logging_changed(None, self.settings['data'] or 'verbose') self._logger.addHandler(self._journal) self._logging_changed_handler = self.preferences_dialog.connect('logging-changed', self._on_logging_changed) def _on_logging_changed(self, prefs_dialog, level): self.settings['data'] = level self._journal.setLevel(LOG_LEVELS[level]) logging.info('setting journald logging level to: {}'.format(level)) def on_disable(self): if self._logging_changed_handler: self.preferences_dialog.disconnect(self._logging_changed_handler) self._logger.removeHandler(self._journal)