The logger middleware for redux-zero
@param config
@returns {function(*): function(*): function(*=)}
420668
function logger(config = {}) {
  // return an middleware
  return store => next => action => {
    const prevState = store.getState();
    const r = next(action);

    function prinf(prev, action, next) {
      console.group(action, "@" + new Date().toISOString());
      console.log("%cprev state", "color:#9E9E9E", prev);
      console.log("%caction", "color:#2196F3", action);
      console.log("%cnext state", "color:#4CAF50", next);
      console.groupEnd();
    }

    if (r && typeof r.then === "function") {
      return next(action).then(
        d =>
          prinf(prevState, action.name, store.getState()) && Promise.resolve(d)
      );
    } else {
      prinf(prevState, action.name, store.getState());
      return r;
    }
  };
}
1066017
function makeLogger(level, method) {
	// The logger function to return takes a variable number of arguments
	// and formats like console.log
	function logger() {
		var args = [].slice.call(arguments);
		var format = level.toUpperCase() + ': (api-client) ' + args.shift();
		var logArgs = [format].concat(args);

		return console[method].apply(console, logArgs);
	}

	return (level === 'warn' || level === 'error' || level === 'info')
		? logger
		: function() {};
}
1167818
function (config) {
    config = config || {};
    Appender.call(this, config);

    /**
     * Log file name, initialized from the configuration. Folders up to the
     * file must exist beforehand.
     * fileName is really the _base_ file name. The real file names will be
     * prepended by a timestamp.
     */
    this.fileName = config.fileName;

    /**
     * The policy used to determine when we should roll the log file. It can be 
     * either time based (roll every x mins), size based (roll when the size
     * of the file is more than x bytes), or both (the first one happening).
     * { time: <timeInMinutes>, size: <sizeInBytes> }
     */
    this.triggeringPolicy = config.triggeringPolicy;

    /**
     * True to log strings instead of objects
     */
    this.appendStrings = (typeof config.appendStrings !== 'undefined') ?
      config.appendStrings :
      true;

    /**
     * The file stream, initialized by the "start" function
     */
    this.stream = null;
  }
1271197
function (build, logger) {
                //Make sure config has a log level, and if not,
                //make it "silent" by default.
                config.logLevel = config.hasOwnProperty('logLevel') ?
                                  config.logLevel : logger.SILENT;

                //Reset build internals first in case this is part
                //of a long-running server process that could have
                //exceptioned out in a bad state. It is only defined
                //after the first call though.
                if (requirejs._buildReset) {
                    requirejs._buildReset();
                    requirejs._cacheReset();
                }

                var result = build(config);

                //And clean up, in case something else triggers
                //a build in another pathway.
                requirejs._buildReset();
                requirejs._cacheReset();

                if (callback) {
                    callback(result);
                }
            }
947469
def _configure_logger(fmt, quiet, level, fpath,
    pre_hooks, post_hooks, metric_grouping_interval):
    

    # NOTE not thread safe. Multiple BaseScripts cannot be instantiated concurrently.
    level = getattr(logging, level.upper())

    global _GLOBAL_LOG_CONFIGURED
    if _GLOBAL_LOG_CONFIGURED:
        return

    # since the hooks need to run through structlog, need to wrap them like processors
    def wrap_hook(fn):
        @wraps(fn)
        def processor(logger, method_name, event_dict):
            fn(event_dict)
            return event_dict

        return processor

    processors = define_log_processors()
    processors.extend(
        [ wrap_hook(h) for h in pre_hooks ]
    )
    if metric_grouping_interval:
        processors.append(metrics_grouping_processor)

    log_renderer = define_log_renderer(fmt, fpath, quiet)
    stderr_required = (not quiet)
    pretty_to_stderr = (
        stderr_required
        and (
            fmt == "pretty"
            or (fmt is None and sys.stderr.isatty())
        )
    )

    should_inject_pretty_renderer = (
        pretty_to_stderr
        and not isinstance(log_renderer, structlog.dev.ConsoleRenderer)
    )
    if should_inject_pretty_renderer:
        stderr_required = False
        processors.append(StderrConsoleRenderer())

    processors.append(log_renderer)
    processors.extend(
        [ wrap_hook(h) for h in post_hooks ]
    )

    streams = []
    # we need to use a stream if we are writing to both file and stderr, and both are json
    if stderr_required:
        streams.append(sys.stderr)

    if fpath is not None:
        # TODO handle creating a directory for this log file ?
        # TODO set mode and encoding appropriately
        streams.append(open(fpath, 'a'))

    assert len(streams) != 0, "cannot configure logger for 0 streams"

    stream = streams[0] if len(streams) == 1 else Stream(*streams)
    atexit.register(stream.close)

    # a global level struct log config unless otherwise specified.
    structlog.configure(
        processors=processors,
        context_class=dict,
        logger_factory=LevelLoggerFactory(stream, level=level),
        wrapper_class=BoundLevelLogger,
        cache_logger_on_first_use=True,
    )

    # TODO take care of removing other handlers
    stdlib_root_log = logging.getLogger()
    stdlib_root_log.addHandler(StdlibStructlogHandler())
    stdlib_root_log.setLevel(level)

    _GLOBAL_LOG_CONFIGURED = True
1054340
static void configJFinal(JFinalConfig jfinalConfig) {
		jfinalConfig.configConstant(constants);			initLogFactory();	initEngine();
		
		configPluginWithOrder(1, jfinalConfig);
		jfinalConfig.configRoute(routes);
		
		configPluginWithOrder(2, jfinalConfig);
		jfinalConfig.configEngine(engine);
		
		configPluginWithOrder(3, jfinalConfig);
		jfinalConfig.configInterceptor(interceptors);
		
		configPluginWithOrder(4, jfinalConfig);
		jfinalConfig.configHandler(handlers);
		
		configPluginWithOrder(5, jfinalConfig);
	}
681812
def get_log_config(component, handlers, level='DEBUG', path='/var/log/vfine/'):
    """"""
    config = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'standard': {
                'format': '%(asctime)s [%(levelname)s][%(threadName)s]' +
                          '[%(name)s.%(funcName)s():%(lineno)d] %(message)s'
            },
            'color': {
                '()': 'shaw.log.SplitColoredFormatter',
                'format': "%(asctime)s " +
                          "%(log_color)s%(bold)s[%(levelname)s]%(reset)s" +
                          "[%(threadName)s][%(name)s.%(funcName)s():%(lineno)d] " +
                          "%(blue)s%(message)s"
            }
        },
        'handlers': {
            'debug': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': path + component + '.debug.log',
                'maxBytes': 1024 * 1024 * 1024,
                'backupCount': 5,
                'formatter': 'standard',
            },
            'color': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': path + component + '.color.log',
                'maxBytes': 1024 * 1024 * 1024,
                'backupCount': 5,
                'formatter': 'color',
            },
            'info': {
                'level': 'INFO',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': path + component + '.info.log',
                'maxBytes': 1024 * 1024 * 1024,
                'backupCount': 5,
                'formatter': 'standard',
            },
            'error': {
                'level': 'ERROR',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': path + component + '.error.log',
                'maxBytes': 1024 * 1024 * 100,
                'backupCount': 5,
                'formatter': 'standard',
            },
            'console': {
                'level': level,
                'class': 'logging.StreamHandler',
                'formatter': 'standard'
            },
        },
        'loggers': {
            'django': {
                'handlers': handlers,
                'level': 'INFO',
                'propagate': False
            },
            'django.request': {
                'handlers': handlers,
                'level': 'INFO',
                'propagate': False,
            },
            '': {
                'handlers': handlers,
                'level': level,
                'propagate': False
            },
        }
    }
    return config
840891
function Preprocessor(config, logger) {
  const log = logger.create('preprocessor.gzip');

  return (content, file, done) => {
    const originalSize = content.length;
    // const contentBuffer = Buffer.isBuffer(content) ? content : Buffer.from(content);

    zlib.gzip(content, (err, gzippedContent) => {
      if (err) {
        log.error(err);
        done(err);
        return;
      }

      // eslint-disable-next-line no-param-reassign
      file.encodings.gzip = gzippedContent;

      log.info(`compressed ${file.originalPath} [${util.bytesToSize(originalSize)} -> ${util.bytesToSize(gzippedContent.length)}]`);
      done(null, content);
    });
  };
}
441238
def log_middleware(store):
    """"""
    def wrapper(next_):
        def log_dispatch(action):
            print('Dispatch Action:', action)
            return next_(action)
        return log_dispatch
    return wrapper
523172
function logger (req, res, next) {
    var now = new Date();

    function logRequest()
    {
        var ok = 200 <= res.statusCode && res.statusCode <= 400;
        if (ok && config.methods.indexOf(req.method) < 0)
            return;
            
        var audit = {
            who: config.user(req),
            when: now.toISOString(),
            where: {
                client: req.ip || req._remoteAddress || (req.connection ? req.connection.remoteAddress : undefined),
                host: req.headers.host,
                server: config.hostname
			},
            why: req.method,
            what: (req.method == 'POST') ? res._headers['location'] : req.url,
            status: res.statusCode,
        };
        sally.log(audit);
    }
    
    onFinished(res, logRequest);
    next();
}
1316145
function init(config){
    var logger = new LogglyLogger(config);
    logger.validateConfig();

    logger.config = config;
    logger.client = loggly.createClient({
        token: config.token,
        subdomain: config.application,
        auth: config.auth,

        // TOOD: pushing more tags onto this array, or not using them, should be configurable
        tags: [
            config.domain,
            config.machine
        ]

        // Loggly docs say it uses json stringify if json:true
        // JSON stringify does not handle Errors or circulare references well
        // Logger.createEntry handles them well
    });
    return logger;
}
1078312
function LoggerContext(logger, module) {
  if (!(this instanceof LoggerContext))
    return new LoggerContext(logger, module);

  assert(typeof module === 'string');

  this.logger = logger;
  this.module = module;
}
628340
function (build, logger) {
                //Make sure config has a log level, and if not,
                //make it "silent" by default.
                config.logLevel = config.hasOwnProperty('logLevel') ?
                                  config.logLevel : logger.SILENT;

                var result = build(config);

                //Reset build internals on each run.
                requirejs._buildReset();

                if (callback) {
                    callback(result);
                }
            }
658082
function createLogger(fn) {
	return function () {
		var args = [],
			self = this,
			c;
		for (c = 0; c < arguments.length; c++) {
			args[c] = logger.specialObjectClone(arguments[c]);
		}
		return fn.apply(self, args);
	};
}
229015
function (config) {
    config = config || {};
    Appender.call(this, config);

    /**
     * Log file name, initialized from the configuration. Folders up to the
     * file must exist beforehand.
     */
    this.fileName = config.fileName;

    /**
     * Append log events to the end of the file when true, clear the file
     * before writing the first log event otherwise.
     */
    this.appendToFile = (typeof config.append !== 'undefined') ?
      !!config.append :
      true;

    /**
     * True to log strings instead of objects
     */
    this.appendStrings = (typeof config.appendStrings !== 'undefined') ?
      config.appendStrings :
      true;

    /**
     * The file stream, initialized by the "start" function
     */
    this.stream = null;
  }
447269
function Logger(opt) {
    var self = {};

    var defaultOptions = {
        name: 'gina', // by default
        template: '%d [ %s ] %m',
        //containers: [],
        levels : { // based on Sylog Severity Levels
            emerg: {
                code: 0,
                label: 'Emergency',
                desciption: 'System is unusable.',
                color: 'red'
            },
            alert: {
                code: 1,
                label: 'Alert',
                desciption: 'Action must be taken immediately.',
                color:'red'
            },

            crit: {
                code: 2,
                label: 'Critical',
                desciption: 'Critical conditions.',
                color: 'red'
            },
            error : {
                code: 3,
                label: 'Error',
                desciption: 'Error conditions.',
                color : 'orange'
            },
            warn : {
                code: 4,
                label: 'Warning',
                desciption: 'Warning conditions.',
                color: 'yellow'
            },
            notice: {
                code: 5,
                label: 'Notice',
                desciption: 'Normal but significant condition.',
                color: 'yellow'
            },
            info : {
                code: 6,
                label: 'Informational',
                desciption: 'Informational messages.',
                color: 'blue'
            },
            debug : {
                code: 7,
                label: 'Debug',
                desciption: 'Debug-level messages.',
                color: 'cyan'
                //'format' : '',
                //'pipe' : []
            }

        }
    };

    if (opt) {
        opt = merge(defaultOptions, opt, true)
    } else {
        opt = defaultOptions
    }

    /**
     * init
     * @constructor
     * */
    var init = function(opt) {
        if ( typeof(Logger.initialized) != "undefined" ) {
            console.debug("Logger instance already exists. Loading it.");
            return getInstance(opt)
        } else {
            Logger.initialized = true;
            Logger.instance = self;
            setDefaultLevels();
        }
    }

    var getInstance = function(opt) {
        return Logger.instance
    }

    var setDefaultLevels = function() {

        for (var l in opt.levels) {
            if ( typeof(self[l]) != 'undefined' )
                delete self[l];

            //self[l] = new Function('return '+write+'('+JSON.stringify(opt)+', '+parse+', "'+l+'", arguments);');
            self[l] = new Function('this._log_printed = false; process.stdout.write('+write+'('+JSON.stringify(opt)+', '+parse+', "'+l+'", arguments));');
        }
    }

    var write = function(opt, parse, s, args) {

        if ( /^(debugger listening on port)/.test(args[0])
            && typeof(opt.levels.info) != 'undefined'
        ) {
            s = 'info'
        }
        //process.stdout.write('\n'+ "LOGGER ACTION ? "+ s + ": ("+args.length+") ["+ args[0]+ "]");
        var content = '';
        //To handle logs with coma separated arguments.
        for (var i=0; i<args.length; ++i) {
            if (args[i] instanceof Function) {
                content += args[i].toString() + ''
            } else if (args[i] instanceof Object) {
                // careful, [ parse ] will be out of the main execution context: passing it for recursive use
                content += parse(parse, args[i], '')
            } else {
                //if ( args[i].replace(/\s/g, '') != '')
                //process.stdout.write('\n'+ ("=>> [" + args[i] + "]"));
                content += args[i] + ' '
            }
        }

        if (content != '' && !this._log_printed) {
            var now = new Date();
            var repl = {
                '%s': s, //severity
                '%d': now, // timestamp
                '%m': content // message
                //'%container', //container
            };

            var patt = opt.template.match(/\%[a-z A-Z 0-9]/g);
            content = opt.template;
            for(var p=0; p<patt.length; ++p) {
                content = content.replace(new RegExp(patt[p], 'g'), repl[patt[p]]);
            }

            //return process.stdout.write('\n'+ content)
            this._log_printed = true;
            return '\n'+ content
        }

        this._log_printed = false;
        return content
    }

    var parse = function(parse, obj, str) {
        var l = 0
            , len = obj.count()
            , isArray = (obj instanceof Array) ? true : false;
        str += (isArray) ? '[ ' : '{';

        for (var attr in obj) {
            ++l;
            if (obj[attr] instanceof Function) {
                str += attr +': [Function]';
                // if you want ot have it all replace by the fllowing line
                //str += attr +':'+ obj[attr].toString();
                str += (l<len) ? ', ' : ''
            } else if (obj[attr] instanceof Object && !isArray) {
                str += '"'+attr+'": ';
                str = parse(parse, obj[attr], str);
                str += (l<len) ? ', ' : '';
            } else {
                if (!isArray && typeof(obj[attr]) == 'string') {
                    str += '"'+attr+'": "' + obj[attr]
                            .replace(/\'/g, "\\'")
                            .replace(/\"/g, '\\"') +'"';
                } else if (isArray) {
                    str += ( typeof(obj[attr]) != 'string' ) ? obj[attr] : '"'+ obj[attr] +'"'
                } else {
                    str += '"'+attr+'": ' + obj[attr]
                }
                str += (l<len) ? ', ' : ''
            }
        }

        str += (isArray) ? ' ]' : '}';
        return str + ' '
    }

//    /**
//     * Add or override existing level(s)
//     * @param {object} levels
//     * */
//    this.addLevel = function(levels) {
//        for (var l in levels) {
//            self[l] = new Function('return '+write+'('+JSON.stringify(opt)+', "'+l+'", arguments);');
//        }
//    }

    self.setLevels = function(levels) {
        try {
            //remove default.
            for (var l in opt.levels) {
                delete self[l]
            }


            for (var l in levels) {
                self[l] = new Function('return '+write+'('+JSON.stringify(opt)+', '+parse+', "'+l+'", arguments);');
            }
        } catch(e) {
            setDefaultLevels();
            self.error('Cannot set type: ', e.stack|| e.message)
        }
    }

    self.getLogger = function(details) {
        console.debug('getting logger')
    }

    self.log = function() {
        var args = arguments, content = '';
        //console.log("arg: ", args);
        //To handle logs with coma speparated arguments.
        for (var i=0; i<args.length; ++i) {

            if (args[i] instanceof Object) {
                //console.log("\n...", args[i], args[i].toString());
                content += JSON.stringify(args[i], null, '\t')
            } else {
                content += args[i]
            }
        }
        //process.stdout.write('\n'+ "hum ? "+ content);
        //console.log("hum ? ", content);
        if (content != '')
            process.stdout.write('\n'+ content)
    }


    init(opt);
    return self
}
52171
function (config) {
  if (!config) {
    config = defaultConfig
  }
  var error = validateConfig(config)
  if (error) {
  }
  config = assign(defaultConfig, config)
  return new BinderLogReader(config)
}