def benchmark(ctx, debug): if debug: chromalog.basicConfig(level=logging.DEBUG) ctx.obj = { 'debug': debug, }
def test_basic_config_add_a_stream_handler(self): logger = logging.Logger('test') self.assertEqual([], logger.handlers) with patch('logging.getLogger', new=lambda: logger): basicConfig() self.assertEqual(1, len(logger.handlers))
def setup_logging(debug): chromalog.basicConfig( level=logging.DEBUG if debug else logging.INFO, format='[%(levelname)s] %(message)s', ) if debug: logging.getLogger('asyncio').setLevel(logging.WARNING) logging.getLogger('azmq').setLevel(logging.WARNING)
def setup_logs(args): '''Load the correct logs' configuration''' if args.verbose: log_conf = VERBOSE elif args.quiet: log_conf = QUIET else: log_conf = BASE chromalog.basicConfig(**log_conf)
def _setup_logging(debug): if debug: chromalog.basicConfig( level=logging.DEBUG, format='[%(levelname)s] %(message)s', ) logging.getLogger('asyncio').setLevel(logging.INFO) else: chromalog.basicConfig( level=logging.INFO, format='%(message)s', )
def main(args=sys.argv[1:], display=StreamDisplay(stream=sys.stdout)): basicConfig(format='%(message)s', level=logging.INFO) params = parse_args(args=args) if params.debug: logger.setLevel(logging.DEBUG) logger.debug("Debug mode enabled.") logger.debug( "Parsed configuration is shown below:\n\n%s\n", yaml_dump(params.configuration, indent=2), ) params.configuration['executor'].execute( environment=os.environ, commands=params.configuration['script'], display=display, )
def create_logger(name: str = LOGGER_NAME, level: int = logging.DEBUG): chromalog.basicConfig(format='%(levelname)s %(message)s', level=logging.ERROR, colorizer=BotBackendColorizer()) log = logging.getLogger(name) log.setLevel(level) # file handler # fh = logging.FileHandler(f'{name}.log') # fh.setLevel(level) # console handler ch = chromalog.ColorizingStreamHandler() ch.setLevel(level) # formatter logging.addLevelName(logging.DEBUG, level_map['debug']) logging.addLevelName(logging.INFO, level_map['info']) logging.addLevelName(logging.WARNING, level_map['warning']) logging.addLevelName(logging.ERROR, level_map['error']) logging.addLevelName(logging.CRITICAL, level_map['critical'])
import urllib import os, sys, re, logging, chromalog from chromalog.mark.helpers.simple import success, error, important chromalog.basicConfig(level=logging.INFO,format="[%(levelname)s] %(message)s") logger = logging.getLogger(__name__) isEnd = False url = "" content = "" pattern = "<a href=\"/photos/(.*?)\"" directory = os.path.expanduser("~/Pictures/unsplash/") if not os.path.exists(directory): logger.info("Creating directory") os.makedirs(directory) page = 1 count = 0 while not isEnd: isEnd = True url = "http://unsplash.com/?page=" + str(page) content = urllib.urlopen(url).read() for s in re.findall(pattern,content): pic = "http://unsplash.com/photos/" + s + "/download" filename = directory + "/" + s + ".jpeg" logger.info("Loading:\t %s", s) if not os.path.exists(filename):
import logging import chromalog chromalog.basicConfig(level=logging.DEBUG) logger = logging.getLogger() logger.debug("This is a debug message") logger.info("This is an info message") logger.warning("This is a warning message") logger.error("This is an error message") logger.critical("This is a critical message")
#!/usr/bin/python2 from flask import Flask, render_template, make_response, jsonify import datetime, random, time from threading import Timer, Thread import RPi.GPIO as GPIO import serial #from flask_cors import CORS import logging, chromalog, re import random from serial import SerialException chromalog.basicConfig(level=logging.DEBUG) #For colored debug terminal #change from .INFO to .DEBUG for more detail logger = logging.getLogger() app = Flask(__name__) #CORS(app, resources=r'/pump/(on|/off)') ser=serial.Serial('/dev/serial0',4800, timeout=5) #Setup GPIO GPIO.setwarnings(False) #remove for debugging GPIO.setmode(GPIO.BCM) GPIO.setup(23,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.setup(24,GPIO.OUT, initial=GPIO.LOW) GPIO.setup(27,GPIO.OUT, initial=GPIO.HIGH) #Relay default:off (active low) #setup serial def update_thread(): logger.debug( "update thread active") line="Default"
import logging import chromalog from chromalog.mark.helpers.simple import success, error, important chromalog.basicConfig(format="%(message)s", level=logging.INFO) logger = logging.getLogger() filename = r'/var/lib/status' logger.info("Booting up system: %s", success("OK")) logger.info("Booting up network: %s", error("FAIL")) logger.info("Reading file at %s: %s", important(filename), success("OK"))
def test_basic_config_sets_format(self): logger = logging.Logger('test') with patch('logging.getLogger', new=lambda: logger): basicConfig(format='my format') self.assertEqual('my format', logger.handlers[0].formatter._fmt)
def test_basic_config_sets_level(self): logger = logging.Logger('test') with patch('logging.getLogger', new=lambda: logger): basicConfig(level=logging.DEBUG) self.assertEqual(logging.DEBUG, logger.level)
def session_logger(): chromalog.basicConfig(level=logging.DEBUG) logger = logging.getLogger("pytest") logger.debug("created session scope logger") return logger
import logging import chromalog import wuphf from test_config import MAIL_01 chromalog.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) log.debug('start create client') w = wuphf.clients.SMTP() log.debug('end create client') log.debug('start create message') msg = wuphf.Message('Test Title', 'Test Body') log.debug('end create message') log.debug('start send') w.send(msg, (MAIL_01)) log.debug('end send')
import logging import os from collections import defaultdict import discord import chromalog import toml # Setup for logging # Log output format LOG_FORMAT = '[%(levelname)s] %(asctime)s %(name)s: %(message)s' DATE_FORMAT = '%Y-%m-%d %H:%M:%S' # Use chromalog for coloured output chromalog.basicConfig(level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT) logger = logging.getLogger('discmulticast') # Shut the discord module up logging.getLogger('discord').setLevel(logging.ERROR) logging.getLogger('websockets').setLevel(logging.ERROR) # Load config logger.info('Loading config') config = toml.load(os.environ['DISCMULTI_CONFIG']) destination_channels = config['dest_ids'] # Create bot class class Bot(discord.Client): """Class implementing bot functionality"""
import sys import MySQLdb as db # CLI Parameter parser = argparse.ArgumentParser("convert-to-sql.py") parser.add_argument("host", help="Datenbankserver") parser.add_argument("username", help="Datenbankbenutzer") parser.add_argument("password", help="Datenbankpasswort") parser.add_argument("database", help="Datenbank") parser.add_argument("--loglevel", help="DEBUG, INFO, ERROR, CRITICAL") args = vars(parser.parse_args()) loglevel = getattr(sys.modules["logging"], args["loglevel"].upper() if args["loglevel"] else "INFO") chromalog.basicConfig(format="%(message)s", level=loglevel) logger = logging.getLogger() # In dieser Tabelle landen die Daten table = "adressdaten" # In diesem Ordner sind wir workDir = os.path.dirname(os.path.realpath(__file__)) # Postleitzahlendatenbank einlesen plzDatei = open(workDir + '/plz_verzeichnis.csv', newline='') plzDict = csv.DictReader(plzDatei) plz = {} for row in plzDict: plz[row["PLZ"]] = (row["Ort"], row["Bundesland"])
def main(): # check dependencies are available check_exe_available('latexpand') # setup docopt and logging args = docopt(__doc__, version='0.1.1') logger_format = '%(asctime)s [%(levelname)s] - %(message)s' chromalog.basicConfig( level=logging.DEBUG if args['--verbose'] else logging.INFO, format=logger_format) logger = logging.getLogger('texstrip') # disable parser logger logging.getLogger('strip_comments').setLevel(logging.INFO) # the main TeX input file main_file = args['<main>'] logger.info('using {} as the main file'.format(main_file)) # create the target dir output_dir = os.path.join(os.getcwd(), args['--outdir']) os.makedirs(output_dir, exist_ok=True) logger.info("using {} as the output dir".format(output_dir)) # 1) expand the main file target_main_file = os.path.join(output_dir, os.path.basename(main_file)) # names for intermediate files expanded_main_file = os.path.join(output_dir, 'expanded.tex.strip') stripped_main_file = os.path.join(output_dir, 'stripped.tex.strip') if target_main_file == main_file: raise Exception('target main file is the same as the source') cmd = 'latexpand --empty-comments -o {} {}'.format(expanded_main_file, main_file) subprocess.run(cmd, shell=True, check=True) logger.debug('Finished: {}'.format(cmd)) if args['<extra>']: for extra in args['<extra>']: # detect files outside working tree path = pathlib.Path(extra) logging.info("copying %s", path) if str(path.relative_to('.')).startswith('..'): logging.fatal("can't copy files outside current dir %s", extra) sys.exit(1) if path.parent == '.': shutil.copy(path, output_dir) else: new_dir = pathlib.Path(output_dir) / path.parent new_dir.mkdir(parents=True, exist_ok=True) shutil.copy(path, new_dir) # 2) remove comments strip_comments.strip_comments_from_files(expanded_main_file, stripped_main_file) # 3) clean up shutil.copyfile(stripped_main_file, target_main_file) # remove intermediate files unless --keep if not args['--keep']: os.remove(expanded_main_file) os.remove(stripped_main_file) if args['--build']: os.chdir(output_dir) build_cmd = "latexmk -pdf {}".format(target_main_file) subprocess.run(build_cmd, shell=True, check=True) build_cmd = "latexmk -C {}".format(target_main_file) subprocess.run(build_cmd, shell=True, check=True) from chromalog.mark.helpers.simple import success, important logger.info("%s The stripped version is at %s" % (success("Done!"), important(target_main_file)))