下面列出了org.slf4j.ILoggerFactory#ch.qos.logback.classic.joran.JoranConfigurator 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void overrideLoggingConfig() {
URL logbackFile = ITestApplication.class.getResource("/spring-logback.xml");
if (logbackFile != null) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
// Call context.reset() to clear any previous configuration, e.g. default
// configuration. For multi-step configuration, omit calling context.reset().
context.reset();
configurator.doConfigure(logbackFile);
} catch (JoranException je) {
// StatusPrinter will handle this
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
}
public static void loadFileConfig(String configFilePath) throws IOException, JoranException {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
File externalConfigFile = new File(configFilePath);
if (!externalConfigFile.isFile()) {
throw new IOException("logback config file not exists. configFilePath = " + configFilePath);
}
if (!externalConfigFile.canRead()) {
throw new IOException("logback config file cannot be read. configFilePath = " + configFilePath);
}
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(configFilePath);
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
/**
* @return The list of log levels configured and their settings
*/
@RequestMapping(value = "reset", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> reset() {
final LoggerContext ctx = (LoggerContext) LoggerFactory.getILoggerFactory();
synchronized (ctx) {
File configuration = ConfigurationWatchListUtil.getConfigurationWatchList(ctx).getCopyOfFileWatchList().get(0);
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(ctx);
ctx.reset();
try {
configurator.doConfigure(configuration);
} catch (JoranException e) {
log.error("Error re-applying the configuration");
}
}
return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
public void configureByResource(URL url) throws JoranException {
if (url == null) {
throw new IllegalArgumentException("URL argument cannot be null");
}
final String urlString = url.toString();
if (urlString.endsWith("groovy")) {
if (EnvUtil.isGroovyAvailable()) {
// avoid directly referring to GafferConfigurator so as to avoid
// loading groovy.lang.GroovyObject . See also http://jira.qos.ch/browse/LBCLASSIC-214
GafferUtil.runGafferConfiguratorOn(loggerContext, this, url);
} else {
StatusManager sm = loggerContext.getStatusManager();
sm.add(new ErrorStatus("Groovy classes are not available on the class path. ABORTING INITIALIZATION.", loggerContext));
}
} else if (urlString.endsWith("xml")) {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(loggerContext);
configurator.doConfigure(url);
} else {
throw new LogbackException("Unexpected filename extension of file [" + url.toString() + "]. Should be either .groovy or .xml");
}
}
@Override
public void start() {
LOGGER.warn("Plugin::" + getClass().getSimpleName() + "::start");
try (InputStream logbackCnfgStream = new BufferedInputStream(DapengContainer.loadInputStreamInClassLoader("logback.xml"))) {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(logbackCnfgStream);
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
} catch (Exception e) {
LOGGER.error("LogbackContainer failed, ignoring ..." + e.getMessage(), e);
// throw new RuntimeException(e);
}
}
public static void initLog() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator jc = new JoranConfigurator();
jc.setContext(context);
context.reset();
String env = System.getProperty("system.environment");
if(StringUtils.isBlank(env)) {
System.err.println("get system.environment error");
throw new RuntimeException("can't get env, service stop!");
}
URL tmpConfigFIleStr = Startup.class.getResource("/logback-" + env + ".xml");
try {
System.out.println("start with configFile : " + tmpConfigFIleStr);
jc.doConfigure(tmpConfigFIleStr);
log.info("load logback config --> " + tmpConfigFIleStr.getFile());
} catch (JoranException e) {
System.err.println(tmpConfigFIleStr + " not exist");
throw new RuntimeException(e);
}
}
private static void setupLogback() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger.info("Setting up Logback");
Logger.info("Application running from: {}", Start.getApplicationDirectory().getAbsolutePath());
System.setProperty("application.home", Start.getApplicationDirectory().getAbsolutePath());
File xmlConfig = new File(new File(Start.getApplicationDirectory(), "conf"), "application-logger.xml");
if (xmlConfig.exists()) {
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(xmlConfig);
} catch (JoranException je) {
// StatusPrinter will handle this
}
}
//System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO, Logger.underlying()), true));
System.setErr(new PrintStream(new LoggerOutputStream(Level.OFF, Logger.underlying()), true));
Logger.info("Logback Setup");
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
public static void load() throws JoranException {
final String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<configuration debug=\"true\">\n" +
"\t<appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n" +
"\t\t<encoder>\n" +
"\t\t\t<charset>UTF-8</charset>\n" +
"\t\t\t<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>\n" +
"\t\t</encoder>\n" +
"\t</appender>\n" +
"\t<root level=\"INFO\">\n" +
"\t\t<appender-ref ref=\"STDOUT\"/>\n" +
"\t</root>\n" +
"</configuration>";
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(new ByteArrayInputStream(s.getBytes(Charset.forName("UTF-8"))));
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
private void initializeLogback() {
Path logbackFilePath = Paths.get(configPath, "logback.xml");
if (logbackFilePath.toFile().exists()) {
try {
// Load logback configuration
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
configurator.doConfigure(logbackFilePath.toFile());
// Install java.util.logging bridge
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
} catch (JoranException e) {
throw new GossipInitializeException("Misconfiguration on logback.xml, check it.", e);
}
}
}
private static void configureLogger(String logDir, String logLevel, String logbackConf) {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
if (!logDir.endsWith(File.separator))
logDir+= File.separator;
context.putProperty("LOG_DIR", logDir);
context.putProperty("LOG_LEVEL", logLevel);
InputStream is = classloader.getResourceAsStream(logbackConf);
configurator.doConfigure(is);
} catch (JoranException je) {
LOG.warn("Cannot configure logger. Continue to execute the command.", je);
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
final String settings = environment.getProperty("logging.config.src");
if (StringUtils.hasText(settings)) {
try {
final ContextBase context = (ContextBase) StaticLoggerBinder.getSingleton().getLoggerFactory();
final JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
LOG.info("try to update logback configuration to {}", settings);
context.reset();
configurator.doConfigure(new ByteArrayInputStream(settings.getBytes()));
} catch (JoranException e) {
LOG.error("can't load settings", e);
}
}
}
/**
* Initialises logging for Waltz. This will attempt to locate a
* file called <code>waltz-logback.xml</code> from either:
* <ul>
* <li>
* root of classpath
* </li>
* <li>
* directory: <code>${user.home}/.waltz</code>
* </li>
* </ul>
*
* Note: this file is allowed to use System.out to communicate
* failures to the operator.
*/
public static void configureLogging() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
context.reset();
configurator.setContext(context);
System.out.println("Attempting to load logback configuration file: " + LOG_CONFIG_FILE_NAME
+ " from classpath or " + System.getProperty("user.home") + "/.waltz/");
Resource logbackConfigFile = IOUtilities.getFileResource(LOG_CONFIG_FILE_NAME);
if (logbackConfigFile.exists()) {
System.out.println("Found logback configuration file: " + logbackConfigFile);
try (InputStream configInputStream = logbackConfigFile.getInputStream()) {
configurator.doConfigure(configInputStream);
}
} else {
System.out.println("Logback configuration file not found..");
}
} catch (IOException | JoranException e) {
// StatusPrinter will handle this
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
@Override
public void contextInitialized(ServletContextEvent event) {
// 从web.xml中加载指定文件名的日志配置文件
String logbackConfigLocation = event.getServletContext().getInitParameter(CONFIG_LOCATION);
InputStream fn = event.getClass().getClassLoader().getResourceAsStream(logbackConfigLocation);
if (fn == null) {
return;
}
try {
LoggerContext loggerContext = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();
loggerContext.reset();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext(loggerContext);
joranConfigurator.doConfigure(fn);
logger.debug("loaded slf4j configure file from " + fn);
} catch (JoranException e) {
logger.error("can loading slf4j configure file from " + fn, e);
}
}
public void testUdpSender() throws JoranException, InterruptedException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog4j-udp.xml"));
Logger logger = context.getLogger("test-udp");
logger.info("test message over udp");
context.stop();
Thread.sleep(100);
final String serverData = serverStream.toString();
assertTrue("Server received: " + serverData, serverData.contains("test message over udp"));
}
public void testTcpSender() throws JoranException, InterruptedException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog4j-tcp.xml"));
Logger logger = context.getLogger("test-tcp");
logger.info("test message over tcp");
context.stop();
Thread.sleep(100);
final String serverData = serverStream.toString();
assertTrue("Server received: " + serverData, serverData.contains("test message over tcp"));
}
public void testTlsSender() throws JoranException, InterruptedException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog4j-tls.xml"));
Logger logger = context.getLogger("test-tls");
logger.info("test message over tls");
context.stop();
Thread.sleep(100);
final String serverData = serverStream.toString();
assertTrue("Server received: " + serverData, serverData.contains("test message over tls"));
}
/**
* Reloads logging.
*
* @param logbackConfig XML containing the logback configuration
*/
public void reloadLogging(String logbackConfig) {
LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(logContext);
logContext.reset();
configurator.doConfigure(new ByteArrayInputStream(logbackConfig.getBytes(Charsets.UTF_8)));
} catch (JoranException je) {
// StatusPrinter will handle this
} catch (Exception ex) {
ex.printStackTrace(); // Just in case, so we see a stacktrace
}
StatusPrinter.printInCaseOfErrorsOrWarnings(logContext);
applicationContext.publishEvent(new LoggingReloadedApplicationEvent(this));
}
/**
* Initializes the logging framework.
* The automatic configuration is reset and the logger is configured dynamically:
* - The log folder is set
* - The log configuration is loaded (not from resources, but from the working directory).
*
* This allows switching the folder and the configuration during development and at deployment.
*/
private void initializeLogging() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator jc = new JoranConfigurator();
jc.setContext(context);
// override default configuration
context.reset();
// inject the location of the appdata log folder as "LOG_FOLDER"
// property of the LoggerContext
context.putProperty("LOG_FOLDER", AppData.getLogFolder().toString());
jc.doConfigure(LOG_CONFIGURATION);
} catch (JoranException je) {
// status printer will handle printing of error
}
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
logger.debug("Initialized logging (LOG_FOLDER={})", context.getProperty("LOG_FOLDER"));
}
private void init() {
// Assumes LSF4J is bound to logback
context = (LoggerContext) LoggerFactory.getILoggerFactory();
// store the home dir to use for relative paths
context.putProperty("stash.home", homeDir);
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
InputStream is;
is = this.getClass().getClassLoader().getResourceAsStream("logback-test.xml");
if (is != null) {
stashRootLogger.info("Using logback-test.xml for logger settings");
} else {
stashRootLogger.info("Using logback.xml for logger settings");
is = this.getClass().getClassLoader().getResourceAsStream("logback.xml");
}
try {
configurator.doConfigure(is);
} catch (JoranException e) {
System.err.println("Error configuring logging framework" + e);
}
stashRootLogger.info("Logger using stash.home of " + homeDir);
}
public static void main(String[] args)
{
URL url = Thread.currentThread().getContextClassLoader().getResource("joran_test.xml");
//加载配置文件 然后获取logger 打印日志
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
// Call context.reset() to clear any previous configuration, e.g. default
// configuration. For multi-step configuration, omit calling context.reset().
context.reset();
configurator.doConfigure(url.getPath());
// logger.info("哈哈哈哈");
} catch (JoranException je) {
// StatusPrinter will handle this
je.printStackTrace();
return;
}
logger.info("哈哈哈哈哈哈||{}",1111);
}
public static void main(String[] args) throws InterruptedException
{
URL url = Thread.currentThread().getContextClassLoader().getResource("logback_thread.xml");
//加载配置文件 然后获取logger 打印日志
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
// Call context.reset() to clear any previous configuration, e.g. default
// configuration. For multi-step configuration, omit calling context.reset().
context.reset();
configurator.doConfigure(url.getPath());
} catch (JoranException je) {
// StatusPrinter will handle this
je.printStackTrace();
return;
}
//文件名
TestThreadLogger testThreadLogger = new TestThreadLogger();
testThreadLogger.start();
TestThreadLogger testThreadLogger1 = new TestThreadLogger();
testThreadLogger1.start();
TestThreadLogger testThreadLogger2 = new TestThreadLogger();
testThreadLogger2.start();
testThreadLogger.join();
testThreadLogger1.join();
testThreadLogger2.join();
}
@Before
public void init() throws JoranException {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(new File("src/test/resources/logback-example.xml"));
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
private static void initLogback() throws JoranException {
String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
}
@Before
public void initLogback() throws JoranException {
InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
System.setProperty("loggingDir", loggingDir);
ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext((Context) iLoggerFactory);
URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
if (logbackConfigFile == null) {
throw new RuntimeException("can't find logback_test.xml");
} else {
joranConfigurator.doConfigure(logbackConfigFile);
}
}
@Before
public void init() throws JoranException {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(new File("src/test/resources/logback-example.xml"));
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
private static void initLogback() throws JoranException {
String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
}
@Before
public void initLogback() throws JoranException {
InternalLoggerFactory.setCurrentLoggerType(InternalLoggerFactory.LOGGER_SLF4J);
System.setProperty("loggingDir", loggingDir);
ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext((Context) iLoggerFactory);
URL logbackConfigFile = Slf4jLoggerFactoryTest.class.getClassLoader().getResource("logback_test.xml");
if (logbackConfigFile == null) {
throw new RuntimeException("can't find logback_test.xml");
} else {
joranConfigurator.doConfigure(logbackConfigFile);
}
}
@Before
public void init() throws JoranException {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(new File("src/test/resources/logback-example.xml"));
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
}
private static void initLogback() throws JoranException {
String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml");
}
/**
* Overrides the standard Logging configuration delivered with HiveMQ with
* a logback.xml from the config folder.
*
* @return If the default configuration was overridden
*/
private static boolean overrideLogbackXml(final @NotNull File configFolder) {
final File file = new File(configFolder, "logback.xml");
if (file.canRead()) {
log.info("Log Configuration was overridden by {}", file.getAbsolutePath());
final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
context.reset();
final JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
configurator.doConfigure(file);
context.getLogger(Logger.ROOT_LOGGER_NAME).addAppender(listAppender);
return true;
} catch (final JoranException je) {
// StatusPrinter will handle this
} catch (final Exception ex) {
// Just in case, so we see a stacktrace if the logger could not be initialized
ex.printStackTrace();
} finally {
StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}
// Print internal status data in case of warnings or errors.
return false;
} else {
log.warn(
"The logging configuration file {} does not exist. Using HiveMQ default logging configuration.",
file.getAbsolutePath());
return false;
}
}