use of ch.qos.logback.classic.encoder.PatternLayoutEncoder in project UniversalMediaServer by UniversalMediaServer.
the class LoggingConfig method forceVerboseFileEncoder.
public static synchronized void forceVerboseFileEncoder() {
final String timeStampFormat = "yyyy-MM-dd HH:mm:ss.SSS";
if (loggerContext == null) {
LOGGER.error("Unknown loggerContext, aborting buffered logging. Make sure that loadFile() has been called first.");
return;
}
// Build iterator
Iterators<Appender<ILoggingEvent>> iterators = new Iterators<>();
// Add CacheLogger or rootLogger appenders depending on whether CacheLogger is active.
if (CacheLogger.isActive()) {
iterators.addIterator(CacheLogger.iteratorForAppenders());
} else {
iterators.addIterator(rootLogger.iteratorForAppenders());
}
// If syslog is active there probably are detached appenders there as well
if (!syslogDetachedAppenders.isEmpty()) {
iterators.addList(syslogDetachedAppenders);
}
// Iterate
Iterator<Appender<ILoggingEvent>> it = iterators.combinedIterator();
while (it.hasNext()) {
Appender<ILoggingEvent> appender = it.next();
if (appender instanceof OutputStreamAppender && !(appender instanceof ConsoleAppender<?>)) {
// Appender has Encoder property
Encoder<ILoggingEvent> encoder = ((OutputStreamAppender<ILoggingEvent>) appender).getEncoder();
if (encoder instanceof PatternLayoutEncoder) {
// Encoder has pattern
PatternLayoutEncoder patternEncoder = (PatternLayoutEncoder) encoder;
String logPattern = patternEncoder.getPattern();
// Set timestamp format
Pattern pattern = Pattern.compile("%((date|d)(\\{([^\\}]*)\\})?)(?=\\s)");
Matcher matcher = pattern.matcher(logPattern);
if (matcher.find()) {
boolean replace = true;
if (matcher.group(4) != null && matcher.group(4).equals(timeStampFormat)) {
replace = false;
}
if (replace) {
logPattern = logPattern.replaceFirst(pattern.pattern(), "%d{" + timeStampFormat + "}");
}
} else {
if (logPattern.startsWith("%-5level")) {
logPattern = logPattern.substring(0, 8) + " %d{" + timeStampFormat + "}" + logPattern.substring(8);
} else {
logPattern = "d%{" + timeStampFormat + "} " + logPattern;
}
}
// Make sure %logger is included
pattern = Pattern.compile("((%logger|%lo|%c)(\\{\\d+\\})?)(?=\\s)");
matcher = pattern.matcher(logPattern);
if (matcher.find()) {
boolean replace = true;
if (matcher.group().equals("%logger")) {
replace = false;
}
if (replace) {
logPattern = logPattern.replaceFirst(pattern.pattern(), "%logger");
}
} else {
if (logPattern.contains("%msg")) {
logPattern = logPattern.substring(0, logPattern.indexOf("%msg")) + "%logger " + logPattern.substring(logPattern.indexOf("%msg"));
} else {
logPattern = "%logger " + logPattern;
}
}
// Activate changes
patternEncoder.setPattern(logPattern);
patternEncoder.start();
}
}
}
LOGGER.info("Verbose file logging pattern enforced");
}
use of ch.qos.logback.classic.encoder.PatternLayoutEncoder in project pom-manipulation-ext by release-engineering.
the class Cli method run.
public int run(String[] args) {
Options options = new Options();
options.addOption("h", false, "Print this help message.");
options.addOption(Option.builder("d").longOpt("debug").desc("Enable debug").build());
options.addOption(Option.builder("t").longOpt("trace").desc("Enable trace").build());
options.addOption(Option.builder("h").longOpt("help").desc("Print help").build());
options.addOption(Option.builder("f").longOpt("file").hasArgs().numberOfArgs(1).desc("POM file").build());
options.addOption(Option.builder().longOpt("log-context").desc("Add log-context ID").numberOfArgs(1).build());
options.addOption(Option.builder("l").longOpt("log").desc("Log file to output logging to").numberOfArgs(1).build());
options.addOption(Option.builder("s").longOpt("settings").hasArgs().numberOfArgs(1).desc("Optional settings.xml file").build());
options.addOption(Option.builder("P").longOpt("activeProfiles").desc("Comma separated list of active profiles.").numberOfArgs(1).build());
options.addOption(Option.builder("o").longOpt("outputFile").desc("outputFile to output dependencies to. Only used with '-p' (Print all project dependencies)").numberOfArgs(1).build());
options.addOption(Option.builder("p").longOpt("printDeps").desc("Print all project dependencies").build());
options.addOption(Option.builder().longOpt("printGAVTC").desc("Print all project dependencies in group:artifact:version:type:classifier with scope information").build());
options.addOption(Option.builder("D").hasArgs().numberOfArgs(2).valueSeparator('=').desc("Java Properties").build());
options.addOption(Option.builder("x").hasArgs().numberOfArgs(2).desc("XPath tester ( file : xpath )").build());
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
logger.debug("Caught problem parsing ", e);
System.err.println(e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("...", options);
return 10;
}
if (cmd.hasOption('h')) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("...", options);
System.exit(0);
}
if (cmd.hasOption('D')) {
userProps = cmd.getOptionProperties("D");
}
if (cmd.hasOption('f')) {
target = new File(cmd.getOptionValue('f'));
}
if (cmd.hasOption('s')) {
settings = new File(cmd.getOptionValue('s'));
}
if (cmd.hasOption("log-context")) {
String mdc = cmd.getOptionValue("log-context");
if (isNotEmpty(mdc)) {
// Append a space to split up level and log-context markers.
MDC.put("LOG-CONTEXT", mdc + ' ');
}
}
createSession(target, settings);
final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
if (cmd.hasOption('l')) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%mdc{LOG-CONTEXT}%level %logger{36} %msg%n");
ple.setContext(loggerContext);
ple.start();
FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
fileAppender.setEncoder(ple);
fileAppender.setContext(loggerContext);
fileAppender.setName("fileLogging");
fileAppender.setAppend(false);
fileAppender.setFile(cmd.getOptionValue("l"));
fileAppender.start();
root.addAppender(fileAppender);
root.setLevel(Level.INFO);
}
// creation stuff.
if (cmd.hasOption('d')) {
root.setLevel(Level.DEBUG);
}
if (cmd.hasOption('t')) {
root.setLevel(Level.TRACE);
}
if (!session.isEnabled()) {
logger.info("Manipulation engine disabled via command-line option");
return 0;
}
if (!target.exists()) {
logger.info("Manipulation engine disabled. Project {} cannot be found.", target);
return 10;
} else // Don't bother skipping if we're just trying to analyse deps.
if (new File(target.getParentFile(), ManipulationManager.MARKER_FILE).exists() && !cmd.hasOption('p')) {
logger.info("Skipping manipulation as previous execution found.");
return 0;
}
try {
Properties config = new ConfigIO().parse(target.getParentFile());
String value = session.getUserProperties().getProperty("allowConfigFilePrecedence");
if (isNotEmpty(value) && "true".equalsIgnoreCase(value)) {
session.getUserProperties().putAll(config);
} else {
for (String key : config.stringPropertyNames()) {
if (!session.getUserProperties().containsKey(key)) {
session.getUserProperties().setProperty(key, config.getProperty(key));
}
}
}
} catch (ManipulationException e) {
logger.error("POM Manipulation failed: Unable to read config file ", e);
return 10;
}
try {
// Note : don't print out settings information earlier (like when we actually read it) as the logging
// isn't setup then.
logger.debug("Using local repository \n{} and found global settings file in {} with contents \n{} and user settings file in {} with contents \n{}", session.getLocalRepository(), DEFAULT_GLOBAL_SETTINGS_FILE, DEFAULT_GLOBAL_SETTINGS_FILE.exists() ? FileUtils.readFileToString(DEFAULT_GLOBAL_SETTINGS_FILE) : "** File does not exist **", settings, (settings != null && settings.exists()) ? FileUtils.readFileToString(settings) : "** File does not exist **");
manipulationManager.init(session);
Set<String> activeProfiles = null;
if (cmd.hasOption('P')) {
activeProfiles = new HashSet<>();
Collections.addAll(activeProfiles, cmd.getOptionValue('P').trim().split(","));
session.getUserProperties().setProperty(PROFILE_SCANNING, "true");
session.getActiveProfiles().addAll(activeProfiles);
}
if (cmd.hasOption('x')) {
String[] params = cmd.getOptionValues('x');
if (params.length != 2) {
throw new ManipulationException("Invalid number of parameters (" + params.length + "); should be <file> <xpath>");
}
XMLIO xmlIO = new XMLIO();
Document doc = xmlIO.parseXML(new File(params[0]));
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.evaluate(params[1], doc, XPathConstants.NODESET);
logger.info("Found {} node", nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
logger.info("Found node {} and value {} ", node.getNodeName(), node.getTextContent());
}
} else if (cmd.hasOption('p') || cmd.hasOption("printGAVTC")) {
Set<ArtifactRef> ts = RESTCollector.establishAllDependencies(session, pomIO.parseProject(session.getPom()), activeProfiles);
logger.info("Found {} dependencies. {}", ts.size(), ts);
File output = null;
if (cmd.hasOption('o')) {
output = new File(cmd.getOptionValue('o'));
output.delete();
}
for (ArtifactRef a : ts) {
String scope = null;
if (a instanceof SimpleScopedArtifactRef) {
scope = ((SimpleScopedArtifactRef) a).getScope();
}
if (cmd.hasOption('o')) {
if (cmd.hasOption("printGAVTC")) {
FileUtils.writeStringToFile(output, String.format("%-80s%10s\n", a, scope), true);
} else {
FileUtils.writeStringToFile(output, a.asProjectVersionRef().toString() + '\n', true);
}
} else {
if (cmd.hasOption("printGAVTC")) {
System.out.format("%-80s%10s\n", a, scope);
} else {
System.out.println(a.asProjectVersionRef());
}
}
}
} else {
manipulationManager.scanAndApply(session);
}
} catch (ManipulationException e) {
logger.error("POM Manipulation failed; original error is {}", e.getMessage());
logger.debug("POM Manipulation error trace is", e);
return 10;
} catch (RestException e) {
logger.error("REST communication with {} failed. {}", userProps.getProperty("restURL"), e.getMessage());
logger.trace("Exception trace is", e);
return 100;
} catch (Exception e) {
logger.error("POM Manipulation failed.", e);
return 100;
}
return 0;
}
use of ch.qos.logback.classic.encoder.PatternLayoutEncoder in project pom-manipulation-ext by release-engineering.
the class TestUtils method runCli.
/**
* Run pom-manipulation-cli via run() with java params (-D arguments) in workingDir directory.
*
* @param args - List of additional command line arguments
* @param params - Map of String keys and String values representing -D arguments
* @param workingDir - Working directory in which you want the cli to be run.
* @return Exit value
* @throws Exception if an error occurs
*/
public static Integer runCli(List<String> args, Map<String, String> params, String workingDir) throws Exception {
ArrayList<String> arguments = new ArrayList<>(args);
Collections.addAll(arguments, toJavaParams(params).split("\\s+"));
boolean argsContainsFile = false;
for (String s : args) {
if (s.startsWith("--file")) {
argsContainsFile = true;
}
}
if (!argsContainsFile) {
arguments.add("--log=" + workingDir + File.separator + "build.log");
arguments.add("--file=" + workingDir + File.separator + "pom.xml");
}
logger.info("Invoking CLI with {} ", arguments);
int result = new Cli().run(arguments.toArray(new String[arguments.size()]));
// This is a bit of a hack. The CLI, if log-to-file is enabled resets the logging. As we don't fork and run
// in the same process this means we need to reset it back again. The benefit of not forking is a simpler test
// harness and it saves time when running the tests.
final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("[%t] %level %logger{32} - %msg%n");
ple.setContext(loggerContext);
ple.start();
ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
consoleAppender.setEncoder(ple);
consoleAppender.setContext(loggerContext);
consoleAppender.start();
root.addAppender(consoleAppender);
root.setLevel(Level.DEBUG);
return result;
}
use of ch.qos.logback.classic.encoder.PatternLayoutEncoder in project solr-document-store by DBCDK.
the class AsyncJob method initLog.
/**
* Set up logging for this class
*
* @param wesocketAppender Optional websocket appender to notify with log.
* If undesired, null can safely be passed instead
* @throws IOException in case of file errors
*/
final void initLog(AsyncJobWesocketAppender wesocketAppender) throws IOException {
UUID uuid = UUID.randomUUID();
this.id = uuid.toString();
this.file = File.createTempFile("/tmp/async-", ".log");
this.write = new FileOutputStream(file);
this.read = new RandomAccessFile(file, "r");
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
this.log = context.getLogger(id);
log.setLevel(Level.DEBUG);
this.appender = new OutputStreamAppender();
appender.setName(id);
appender.setContext(log.getLoggerContext());
appender.setOutputStream(write);
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(context);
encoder.setPattern(getLogPattern() + "%msg%n%rEx");
// Not really sure why this is nessecary appender.setEncoder should do that
encoder.init(write);
encoder.start();
appender.setEncoder(encoder);
appender.start();
log.addAppender(appender);
if (wesocketAppender != null) {
// Setup notifier using websocket to push updates to frontend
// this.wsAppender = new AsyncJobWesocketAppender(uuid,name,sessionHandler);
this.wsAppender = wesocketAppender;
wsAppender.setContext(log.getLoggerContext());
wsAppender.start();
log.addAppender(wsAppender);
}
}
use of ch.qos.logback.classic.encoder.PatternLayoutEncoder in project accent4j by cinchapi.
the class Logger method setup.
/**
* Programmatically configure an internal logger.
*
* @param name the name of the internal logger
* @param file the the internal logger uses
* @return the internal logger
*/
private ch.qos.logback.classic.Logger setup(String name, String file) {
if (!enableConsoleLogging) {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
root.detachAndStopAllAppenders();
}
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
// Configure Pattern
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setPattern("%date [%thread] %level - %msg%n");
encoder.setContext(context);
encoder.start();
// Create File Appender
RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<ILoggingEvent>();
appender.setFile(directory + File.separator + file);
appender.setContext(context);
// Configure Rolling Policy
FixedWindowRollingPolicy rolling = new FixedWindowRollingPolicy();
rolling.setMaxIndex(1);
rolling.setMaxIndex(5);
rolling.setContext(context);
rolling.setFileNamePattern(directory + File.separator + file + ".%i.zip");
rolling.setParent(appender);
rolling.start();
// Configure Triggering Policy
SizeBasedTriggeringPolicy<ILoggingEvent> triggering = new SizeBasedTriggeringPolicy<ILoggingEvent>();
triggering.setMaxFileSize(maxFileSize);
triggering.start();
// Configure File Appender
appender.setEncoder(encoder);
appender.setRollingPolicy(rolling);
appender.setTriggeringPolicy(triggering);
appender.start();
// Get Logger
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(name);
logger.addAppender(appender);
logger.setLevel(level);
logger.setAdditive(true);
return logger;
}
Aggregations