Created
March 1, 2017 14:31
-
-
Save svaponi/f52022cb78530613d77a4b2f35b10c0e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package it.miriade.infobus.logging; | |
import java.io.File; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.util.Objects; | |
import org.apache.commons.lang3.StringUtils; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.util.Assert; | |
import ch.qos.logback.classic.LoggerContext; | |
import ch.qos.logback.classic.util.ContextInitializer; | |
import ch.qos.logback.core.joran.spi.JoranException; | |
import it.miriade.commons.web.utils.ClasspathLoader; | |
/** | |
* ATTENZIONE: questa era fatta per reinizializzare log4j, con logback dovrebbe | |
* essere più semplice (magari c'è roba in più) | |
* | |
* @author svaponi | |
* @created 2015-03-01 12:04:41 PM | |
*/ | |
public class LogbackInitializer { | |
public static final String LOGBACK_DEFAUL_CONFIG_FILE = "logback.xml"; | |
public static final ClasspathLoader loader = new ClasspathLoader(); | |
private final Logger logger = LoggerFactory.getLogger(this.getClass()); | |
private String configurationFilePath; | |
public static String getConfigurationFilePath() { | |
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); | |
URL url = new ContextInitializer(loggerContext).findURLOfDefaultConfigurationFile(false); | |
return url.getFile(); | |
} | |
public static void reset() { | |
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); | |
loggerContext.reset(); | |
} | |
/** | |
* Configure Logback in current execution. Need to be initiated using | |
* <code>init()</code> method. Suggested use:<br/> | |
* <br/> | |
* | |
* <pre> | |
* new LogbackInitializer().init(); | |
* </pre> | |
*/ | |
public LogbackInitializer() { | |
super(); | |
this.configurationFilePath = LOGBACK_DEFAUL_CONFIG_FILE; | |
} | |
/** | |
* Configure Logback in current execution. Need to be initiated using | |
* <code>init()</code> method. Suggested use:<br/> | |
* | |
* <pre> | |
* new LogbackInitializer("mylogback.xml").init(); | |
* </pre> | |
* | |
* @param configurationFilePath | |
* (path + name) If invalid | |
*/ | |
public LogbackInitializer(String configurationFilePath) { | |
super(); | |
Assert.hasText(configurationFilePath, "Logback configuration filepath is null"); | |
this.configurationFilePath = configurationFilePath; | |
} | |
/** | |
* Initiate and configure Logback in current execution. | |
*/ | |
public LogbackInitializer init() { | |
try { | |
configure(configurationFilePath); | |
} catch (Exception e) { | |
logger.error(e.getMessage(), e); | |
} | |
return this; | |
} | |
/** | |
* Configura il root logger con il xml file in ingresso. Se non trova il xml | |
* file solleva una RuntimeException. | |
* | |
* @param configurationFilePath | |
* path al logback.properties | |
* @throws RuntimeException | |
*/ | |
public void configure(String configurationFilePath) throws RuntimeException { | |
String absolutePath; | |
File configFile = null; | |
/* | |
* controlla i vari casi in cui il path è assoluto | |
*/ | |
if (Objects.toString(configurationFilePath, "").startsWith("file://")) { | |
configFile = new File(configurationFilePath.substring("file://".length())); | |
if (configFile != null && configFile.exists() && configFile.isFile()) | |
absolutePath = configFile.getAbsolutePath(); | |
else | |
throw new RuntimeException("File " + configurationFilePath + " not found"); | |
} else if (Objects.toString(configurationFilePath, "").startsWith("file:")) { | |
configFile = new File(configurationFilePath.substring("file:".length())); | |
if (configFile != null && configFile.exists() && configFile.isFile()) | |
absolutePath = configFile.getAbsolutePath(); | |
else | |
throw new RuntimeException("File " + configurationFilePath + " not found"); | |
} else if (Objects.toString(configurationFilePath, "").startsWith("/")) { | |
configFile = new File(configurationFilePath); | |
if (configFile != null && configFile.exists() && configFile.isFile()) | |
absolutePath = configFile.getAbsolutePath(); | |
else | |
throw new RuntimeException("File " + configurationFilePath + " not found"); | |
} else { | |
// Se il path è relativo lo si cerca dentro al classpath | |
absolutePath = loader.lookForFileOnClasspath(configurationFilePath).getAbsolutePath(); | |
} | |
if (StringUtils.isNotBlank(absolutePath)) | |
try { | |
System.setProperty("logback.configurationFile", absolutePath); | |
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); | |
/* | |
* TODO verificare quale tra i seguenti è il metodo corretto per | |
* caricare il file di configurazione | |
*/ | |
// loggerContext.reset(); | |
// new ContextInitializer(loggerContext).autoConfig(); | |
absolutePath = "file:" + absolutePath; | |
new ContextInitializer(loggerContext).configureByResource(new URL(absolutePath)); | |
logger.info("Logback xml file successfully loaded! [{}]", absolutePath); | |
} catch (JoranException e) { | |
logger.error(e.getMessage()); | |
} catch (MalformedURLException e) { | |
logger.error(e.getMessage()); | |
} | |
else { | |
logger.info("Logback configuration ignored due to a NULL xml file"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package it.miriade.infobus.logging; | |
import javax.servlet.ServletConfig; | |
import javax.servlet.ServletException; | |
import javax.servlet.http.HttpServlet; | |
import org.apache.commons.lang3.StringUtils; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
/** | |
* Per impostare il file da usare uso un init-param in web.xml, oppure una | |
* SystemProperty. Il path può essere un path assoluto, oppure un path relativo | |
* interno all'applicazione/war.<br/> | |
* <br/> | |
* | |
* <strong>Esempio con init-param:</strong> | |
* | |
* <pre> | |
* <code> | |
(init-param) | |
(param-name)log.configuration.file.path(/param-name) | |
(param-value)/absolute/path/to/logback.xml(/param-value) | |
(/init-param) | |
* </code> | |
* </pre> | |
* | |
* <strong>Esempio con SystemProperty:</strong> | |
* | |
* <pre> | |
* <code> | |
-Dmiriade.log.configuration.file.path="file:///absolute/path/to/logback.xml" | |
* </code> | |
* </pre> | |
* | |
* @author svaponi | |
* | |
*/ | |
public class LogbackInitializerServlet extends HttpServlet { | |
private static final long serialVersionUID = 1L; | |
public static final String MIRIADE_PREFIX = "miriade."; | |
/** | |
* Parametro di identificazoine del ambiente corrente: DEVelopment, system TEST, PRODuzione | |
*/ | |
public static final String CURRENTENV = "currentenv"; | |
/** | |
* Nome della proprietà (o <init-param>) con il path al log4j.properties | |
*/ | |
public static final String LOG_CONFIG_FILE_PATH = "log.configuration.file.path"; | |
protected final Logger logger = LoggerFactory.getLogger(this.getClass()); | |
protected LogbackInitializer initializer; | |
/** | |
* Default initialize method called by servlet container. | |
*/ | |
@Override | |
public void init(ServletConfig config) throws ServletException { | |
try { | |
String configurationFilePath = this.getConfigigurationFilePath(config); | |
if (StringUtils.isBlank(configurationFilePath)) { | |
initializer = new LogbackInitializer().init(); | |
} else { | |
initializer = new LogbackInitializer(configurationFilePath).init(); | |
} | |
} catch (Exception e) { | |
logger.error("Log configuration failed! " + e.getMessage(), e); | |
} | |
} | |
/** | |
* Legge il paramentro <code><init-param></code> dalla configurazione | |
* della servlet, ovvero dal web.xml. In caso di parametro mancante | |
* controlla tra le sistem propeties preappendendo l'identificativo di | |
* miriade "-Dmiriade." | |
* | |
* @param config | |
* @return | |
*/ | |
protected String getConfigigurationFilePath(ServletConfig config) { | |
String param = config.getInitParameter(LOG_CONFIG_FILE_PATH); | |
if (StringUtils.isNotBlank(param)) { | |
param = param.trim(); | |
logger.debug("<init-param> \"" + LOG_CONFIG_FILE_PATH + "\" = \"" + param + "\""); | |
} else { | |
param = System.getProperty("-Dmiriade." + LOG_CONFIG_FILE_PATH); | |
if (StringUtils.isNotBlank(param)) | |
logger.debug("<system-property> \"" + LOG_CONFIG_FILE_PATH + "\" = \"" + param + "\""); | |
else | |
logger.warn("Missing parameter \"" + LOG_CONFIG_FILE_PATH + "\", keep default configiguration"); | |
} | |
return param; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package it.miriade.infobus.logging; | |
import javax.servlet.ServletConfig; | |
import org.apache.commons.lang3.StringUtils; | |
/** | |
* In caso abbiamo più applicazioni sullo stesso Tomcat, possiamo aggiungere un suffisso diverso al file di configurazione dei log per ciascuna applicazione. | |
* | |
* <pre> | |
* <code> | |
(init-param) | |
(param-name)log.configuration.file.path.property.suffix(/param-name) | |
(param-value)pippo-e-pluto(/param-value) | |
(/init-param) | |
* <code> | |
* </pre> | |
* E poi settare la SystemProperty: | |
* <pre> | |
* <code> | |
-Dmiriade.log.configuration.file.path.pippo-e-pluto="file:///absolute/path/to/logback.xml" | |
* </code> | |
* </pre> | |
* | |
* @author svaponi | |
* | |
*/ | |
public class LogbackInitializerServletBySystemProperty extends LogbackInitializerServlet { | |
private static final long serialVersionUID = 1L; | |
/** | |
* Parametro che permette di aggiungere un suffisso alla SYSTEM_PROPERTY in modo da identificare una applicazione | |
* tra le altre che condividono lo stesso ambiente (servlet container) e | |
* utilizzano lo stesso LogInitializer. Così è possibile utilizzare diversi file di configurazione. | |
*/ | |
public static final String LOG_CONFIG_FILE_PATH_PROPERTY_SUFFIX = "log.configuration.file.path.property.suffix"; | |
/** | |
* Metodo delegato a recuperare il ConfigigurationFilePath da caricare. Il | |
* path può essere un path assoluto, oppure un path relativo interno | |
* all'applicazione/war. | |
*/ | |
@Override | |
protected String getConfigigurationFilePath(ServletConfig config) { | |
String customsuffix = config.getInitParameter(LOG_CONFIG_FILE_PATH_PROPERTY_SUFFIX); | |
if (StringUtils.isNotBlank(customsuffix)) { | |
customsuffix = "." + customsuffix.trim(); | |
logger.debug("<init-param> {} = \"{}\"", LOG_CONFIG_FILE_PATH_PROPERTY_SUFFIX, customsuffix); | |
} | |
String paramkey = "miriade." + LOG_CONFIG_FILE_PATH + customsuffix; | |
String filePath = System.getProperty(paramkey, ""); | |
logger.debug("<system-property> \"{}\" = \"{}\"", paramkey, filePath); | |
if (StringUtils.isBlank(filePath)) | |
return null; | |
else | |
return filePath; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment