handler the log records to formatted string
176464
def logstr(self):
        """"""

        result = []
        formater = LogFormatter(color=False)
        for record in self.logs:
            if isinstance(record, six.string_types):
                result.append(pretty_unicode(record))
            else:
                if record.exc_info:
                    a, b, tb = record.exc_info
                    tb = hide_me(tb, globals())
                    record.exc_info = a, b, tb
                result.append(pretty_unicode(formater.format(record)))
                result.append(u'\n')
        return u''.join(result)
961267
def formatter_fields_for_record(self, record):
        
        datetime_serialized = (
            datetime.now(timezone.utc).astimezone(self.tz).isoformat()
        )

        default_fields = (
            (LOGGED_AT_FIELDNAME, datetime_serialized),
            (LINE_NUMBER_FIELDNAME, record.lineno),
            (FUNCTION_NAME_FIELDNAME, record.funcName),
            (LOG_LEVEL_FIELDNAME, self.level_to_name_mapping[record.levelno]),
            (FILE_PATH_FIELDNAME, record.pathname),
        )

        for field, value in default_fields:
            if field in self.log_fields:
                yield field, value
1347571
def format(self, record):
        
        formatted = super(IndentingFormatter, self).format(record)
        prefix = ''
        if self.add_timestamp:
            prefix = self.formatTime(record, "%Y-%m-%dT%H:%M:%S ")
        prefix += " " * get_indentation()
        formatted = "".join([
            prefix + line
            for line in formatted.splitlines(True)
        ])
        return formatted
658684
def get_logger(name=None, format_string=None):
    
    logging.captureWarnings(True)
    log = logging.getLogger(name)

    # Bind custom method to instance.
    # Source: https://stackoverflow.com/a/2982
    log.set_debug_level = _set_debug_level.__get__(log)
    log.set_debug_level(0)

    if not format_string:
        format_string = '[%(module)s]\t%(levelname)s\t%(message)s'

    # Setting up log formats
    log.handlers = []
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(
        logging.Formatter(format_string),
    )
    log.addHandler(handler)

    return log
470765
public static void format(LogData logData, SimpleLogHandler receiver) {
    Metadata metadata = logData.getMetadata();
    Throwable thrown = metadata.findValue(LogContext.Key.LOG_CAUSE);
    // Either no metadata, or exactly one "cause" means we don't need to do additional formatting.
    // This is pretty common and will save some work and object allocations.
    boolean hasOnlyKnownMetadata = metadata.size() == 0 || (metadata.size() == 1 && thrown != null);

    TemplateContext ctx = logData.getTemplateContext();
    String message;
    if (ctx == null) {
      // If a literal message (no arguments) is logged and no metadata exists, just use the string.
      // Having no format arguments is fairly common and this avoids allocating StringBuilders and
      // formatter instances in a lot of situations.
      message = safeToString(logData.getLiteralArgument());
      if (!hasOnlyKnownMetadata) {
        // If unknown metadata exists we have to append it to the message (this is not that common
        // because a Throwable "cause" is already handled separately).
        message = appendContext(new StringBuilder(message), metadata);
      }
    } else {
      StringBuilder buffer = formatMessage(logData);
      message = hasOnlyKnownMetadata ? buffer.toString() : appendContext(buffer, metadata);
    }
    receiver.handleFormattedLogMessage(logData.getLevel(), message, thrown);
  }
1256518
private static void formatBadLogData(LogData data, StringBuilder out) {
    out.append("  original message: ");
    if (data.getTemplateContext() == null) {
      out.append(data.getLiteralArgument());
    } else {
      // We know that there's at least one argument to display here.
      out.append(data.getTemplateContext().getMessage());
      out.append("\n  original arguments:");
      for (Object arg : data.getArguments()) {
        out.append("\n    ").append(SimpleMessageFormatter.safeToString(arg));
      }
    }
    Metadata metadata = data.getMetadata();
    if (metadata.size() > 0) {
      out.append("\n  metadata:");
      for (int n = 0; n < metadata.size(); n++) {
        out.append("\n    ");
        out.append(metadata.getKey(n).getLabel()).append(": ").append(metadata.getValue(n));
      }
    }
    out.append("\n  level: ").append(data.getLevel());
    out.append("\n  timestamp (nanos): ").append(data.getTimestampNanos());
    out.append("\n  class: ").append(data.getLogSite().getClassName());
    out.append("\n  method: ").append(data.getLogSite().getMethodName());
    out.append("\n  line number: ").append(data.getLogSite().getLineNumber());
  }
1321405
def format(self, record):
        # type: (logging.LogRecord) -> str
        
        if record.levelno >= logging.ERROR:
            color = colorama.Fore.RED
        elif record.levelno >= logging.WARNING:
            color = colorama.Fore.YELLOW
        elif record.levelno >= logging.INFO:
            color = colorama.Fore.RESET
        else:
            color = colorama.Fore.CYAN
        format_template = (
            '{}{}%(levelname)s{} [%(asctime)s][%(name)s]{} %(message)s')
        if sys.stdout.isatty():
            self._fmt = format_template.format(
                colorama.Style.BRIGHT,
                color,
                colorama.Fore.RESET,
                colorama.Style.RESET_ALL
            )
        else:
            self._fmt = format_template.format(*[''] * 4)
        if six.PY3:
            self._style._fmt = self._fmt  # pylint: disable=protected-access
        return super(_LogColorFormatter, self).format(record)
275262
def format_graylog_v0(self, record):
        '''
        
        '''
        message_dict = {
            'message': record.getMessage(),
            'timestamp': self.formatTime(record),
            # Graylog uses syslog levels, not whatever it is Python does...
            'level': syslog_levels.get(record.levelname, 'ALERT'),
            'tag': self.tag
        }

        if record.exc_info:
            exc_info = self.formatException(record.exc_info)
            message_dict.update({'full_message': exc_info})

        # Add any extra attributes to the message field
        for key, value in six.iteritems(record.__dict__):
            if key in ('args', 'asctime', 'bracketlevel', 'bracketname', 'bracketprocess',
                       'created', 'exc_info', 'exc_text', 'id', 'levelname', 'levelno', 'msecs',
                       'msecs', 'message', 'msg', 'relativeCreated', 'version'):
                # These are already handled above or explicitly pruned.
                continue

            if isinstance(value, (six.string_types, bool, dict, float, int, list, types.NoneType)):  # pylint: disable=W1699
                val = value
            else:
                val = repr(value)
            message_dict.update({'{0}'.format(key): val})
        return message_dict
839937
def format(self, record):
        """"""
        if record.levelno == logging.DEBUG:
            string = Back.WHITE + Fore.BLACK + ' debug '
        elif record.levelno == logging.INFO:
            string = Back.BLUE + Fore.WHITE + ' info '
        elif record.levelno == logging.WARNING:
            string = Back.YELLOW + Fore.BLACK + ' warning '
        elif record.levelno == logging.ERROR:
            string = Back.RED + Fore.WHITE + ' error '
        elif record.levelno == logging.CRITICAL:
            string = Back.BLACK + Fore.WHITE + ' critical '
        else:
            string = ''
        return '{none}{string}{none} {super}'.format(
            none=Style.RESET_ALL, string=string, super=super().format(record))
566458
def format(self, record):
        """"""
        levelname = getattr(record, 'levelname', None)
        record.levelcolor = ''
        record.endlevelcolor = ''

        if levelname:
            level_color = getattr(self.TermColors, levelname, '')
            record.levelcolor = level_color
            record.endlevelcolor = self.TermColors.ENDC if level_color else ''

        return super(FleakerLogFormatter, self).format(record)
367395
@Override
  public String format(LogRecord log)
  {
    StringBuilder sb = new StringBuilder();
    
    int mark = 0;

    for (FormatItem item : _formatList) {
      item.format(sb, log, mark);
      
      if (item instanceof PrettyPrintMarkItem) {
        mark = sb.length();
      }
    }
    
    return sb.toString();
  }
352101
private String format(LogEvent event) {
        JsonObject jsonEvent = new JsonObject();
        jsonEvent.addProperty("v", 0);
        jsonEvent.addProperty("level", BUNYAN_LEVEL.get(event.getLevel()));
        jsonEvent.addProperty("levelStr", event.getLevel().toString());
        jsonEvent.addProperty("name", event.getLoggerName());
        try {
            jsonEvent.addProperty("hostname", InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            jsonEvent.addProperty("hostname", "unkown");
        }
        jsonEvent.addProperty("pid", event.getThreadId());
        jsonEvent.addProperty("time", formatAsIsoUTCDateTime(event.getTimeMillis()));
        jsonEvent.addProperty("msg", event.getMessage().getFormattedMessage());
        jsonEvent.addProperty("src", event.getSource().getClassName());

        if (event.getLevel().isMoreSpecificThan(Level.WARN) && event.getThrown() != null) {
            JsonObject jsonError = new JsonObject();
            Throwable e = event.getThrown();

            jsonError.addProperty("message", e.getMessage());
            jsonError.addProperty("name", e.getClass().getSimpleName());

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            jsonError.addProperty("stack", sw.toString());
            jsonEvent.add("err", jsonError);
        }
        return GSON.toJson(jsonEvent) + "\n";
    }
146417
def format(self, record):
        
        out = dict(
            Timestamp=int(record.created * 1e9),
            Type=record.name,
            Logger=self.logger_name,
            Hostname=self.hostname,
            EnvVersion=self.LOGGING_FORMAT_VERSION,
            Severity=self.SYSLOG_LEVEL_MAP.get(record.levelno,
                                               self.DEFAULT_SYSLOG_LEVEL),
            Pid=record.process,
        )

        # Include any custom attributes set on the record.
        # These would usually be collected metrics data.
        fields = dict()
        for key, value in record.__dict__.items():
            if key not in self.EXCLUDED_LOGRECORD_ATTRS:
                fields[key] = value

        # Only include the 'message' key if it has useful content
        # and is not already a JSON blob.
        message = record.getMessage()
        if message:
            if not message.startswith("{") and not message.endswith("}"):
                fields["msg"] = message

        # If there is an error, format it for nice output.
        if record.exc_info is not None:
            fields["error"] = repr(record.exc_info[1])
            fields["traceback"] = safer_format_traceback(*record.exc_info)

        out['Fields'] = fields

        return json.dumps(out)
1344392
private String createFormattedString(LogRecord logRecord, Object id, String txt) {

        String objId;
        WsLogRecord wsLogRecord = getWsLogRecord(logRecord);

        String name;
        String method = logRecord.getSourceMethodName();
        String className = logRecord.getSourceClassName();

        String stackTrace = getStackTrace(logRecord);
        String sym = getMarker(logRecord);

        StringBuilder sb = new StringBuilder(256);

        // Common header
        sb.append('[').append(DateFormatHelper.formatTime(logRecord.getMillis(), useIsoDateFormat)).append("] ");
        sb.append(DataFormatHelper.getThreadId());

        switch (traceFormat) {
            default:
            case ENHANCED:
                objId = generateObjectId(id, true);
                name = nonNullString(logRecord.getSourceClassName(), logRecord.getLoggerName());

                sb.append(" id=").append(objId).append(' ');
                formatFixedString(sb, name, enhancedNameLength);
                sb.append(sym); // sym has built-in padding
                if (method != null) {
                    sb.append(method).append(' ');
                }

                // append formatted message -- txt includes formatted args
                sb.append(txt);
                if (stackTrace != null)
                    sb.append(LoggingConstants.nl).append(stackTrace);
                break;
            case BASIC:
                name = nonNullString(logRecord.getLoggerName(), logRecord.getSourceClassName());

                sb.append(' '); // pad after thread id
                fixedClassString(sb, name, basicNameLength);
                sb.append(sym);

                if (className != null)
                    sb.append(className);
                sb.append(' '); // yes, this space is always there.

                if (method != null)
                    sb.append(method);
                sb.append(' '); // yes, this space is always there.

                // append formatted message -- includes formatted args
                sb.append(txt);
                if (stackTrace != null)
                    sb.append(nlBasicPadding).append(stackTrace);
                break;
            case ADVANCED:
                objId = generateObjectId(id, false);
                name = nonNullString(logRecord.getLoggerName(), null);

                sb.append(' '); // pad after thread id
                sb.append(sym);

                // next append the correlation id.
                sb.append("UOW=");
                if (wsLogRecord != null)
                    sb.append(wsLogRecord.getCorrelationId());

                // next enter the logger name.
                sb.append(" source=").append(name);

                // append className if non-null
                if (className != null)
                    sb.append(" class=").append(className);

                // append methodName if non-null
                if (method != null)
                    sb.append(" method=").append(method);

                if (id != null)
                    sb.append(" id=").append(objId);

                String x;
                if (wsLogRecord != null) {
                    // next append org, prod, component, if set. Reference equality check is ok here.
                    sb.append(" org=");
                    sb.append(wsLogRecord.getOrganization());
                    sb.append(" prod=");
                    sb.append(wsLogRecord.getProduct());
                    sb.append(" component=");
                    sb.append(wsLogRecord.getComponent());

                    //get thread name
                    x = wsLogRecord.getReporterOrSourceThreadName();
                } else {
                    x = Thread.currentThread().getName();
                }
                if (x != null) {
                    sb.append(" thread=[").append(x).append("]");
                }

                // append formatted message -- txt includes formatted args
                sb.append(nlAdvancedPadding).append(txt);
                if (stackTrace != null)
                    sb.append(nlAdvancedPadding).append(stackTrace);
                break;
        }

        return sb.toString();
    }
1250155
@Override
	public String format (LogRecord logRecord) {
		StringBuilder resultBuilder = new StringBuilder ();
		String prefix = logRecord.getLevel ().getName () + "\t";

		resultBuilder.append (prefix);

		resultBuilder.append (Thread.currentThread ().getName ())
				.append (" ")
				.append (sdf.format (new java.util.Date (logRecord.getMillis ())))
				.append (": ")
				.append (logRecord.getSourceClassName ())
				.append (":")
				.append (logRecord.getSourceMethodName ())
				.append (": ")
				.append (logRecord.getMessage ());

		Object[] params = logRecord.getParameters ();
		if (params != null) {
			resultBuilder.append ("\nParameters:");

			if (params.length < 1) {
				resultBuilder.append (" (none)");
			} else {
				for (int paramIndex = 0; paramIndex < params.length; paramIndex++) {
					Object param = params[paramIndex];
					if (param != null) {
						String paramString = param.toString ();

						resultBuilder.append ("\nParameter ")
								.append (String.valueOf (paramIndex))
								.append (" is a ")
								.append (param.getClass ().getName ())
								.append (": >")
								.append (paramString)
								.append ("<");
					} else {
						resultBuilder.append ("\nParameter ")
								.append (String.valueOf (paramIndex))
								.append (" is null.");
					}
				}
			}
		}

		Throwable t = logRecord.getThrown ();
		if (t != null) {
			resultBuilder.append ("\nThrowing:\n")
					.append (getFullThrowableMsg (t));
		}
		
		String result = resultBuilder.toString ().replaceAll ("\n", "\n" + prefix) + "\n";

		return result;
	}
217428
@Override
  public String format(LogRecord record) {
    String msg = record.getMessage();
    if(msg.length() > 0) {
      if (record instanceof ProgressLogRecord) {
        return msg;
      }
      if(msg.endsWith(OutputStreamLogger.NEWLINE)) {
        return msg;
      }
    }
    return msg + OutputStreamLogger.NEWLINE;
  }
202954
def format(self, record, *args, **kwargs):
        
        return logging.Formatter.format(
            self, record, *args, **kwargs).replace('\n', '\n' + ' ' * 8)