001 package com.github.sarxos.webcam.log; 002 003 import java.io.File; 004 import java.io.FileInputStream; 005 import java.io.FileNotFoundException; 006 import java.io.IOException; 007 import java.io.InputStream; 008 009 import org.slf4j.Logger; 010 import org.slf4j.LoggerFactory; 011 012 import ch.qos.logback.classic.LoggerContext; 013 import ch.qos.logback.classic.joran.JoranConfigurator; 014 import ch.qos.logback.core.joran.spi.JoranException; 015 016 017 /** 018 * Configure loggers. 019 * 020 * @author Bartosz Firyn (SarXos) 021 */ 022 public class WebcamLogConfigurator { 023 024 /** 025 * Logger instance. 026 */ 027 private static final Logger LOG = LoggerFactory.getLogger(WebcamLogConfigurator.class); 028 029 /** 030 * Configure SLF4J. 031 * 032 * @param is input stream to logback configuration xml 033 */ 034 public static void configure(InputStream is) { 035 036 try { 037 Class.forName("ch.qos.logback.classic.LoggerContext"); 038 } catch (ClassNotFoundException e1) { 039 LOG.error("Cannot configure logger because logback LoggerContext is not available in classpath"); 040 return; 041 } 042 043 LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); 044 JoranConfigurator configurator = new JoranConfigurator(); 045 configurator.setContext(context); 046 context.reset(); 047 048 try { 049 configurator.doConfigure(is); 050 } catch (JoranException e) { 051 LOG.error("Joran configuration exception", e); 052 e.printStackTrace(); 053 } 054 } 055 056 /** 057 * Configure SLF4J. 058 * 059 * @param file logback configuration file 060 */ 061 public static void configure(File file) { 062 FileInputStream fis = null; 063 try { 064 fis = new FileInputStream(file); 065 configure(fis); 066 } catch (FileNotFoundException e) { 067 LOG.error("File not found " + file, e); 068 e.printStackTrace(); 069 } finally { 070 if (fis != null) { 071 try { 072 fis.close(); 073 } catch (IOException e) { 074 LOG.error("Cannot close file " + file, e); 075 e.printStackTrace(); 076 } 077 } 078 } 079 } 080 081 /** 082 * Configure SLF4J. 083 * 084 * @param file logback configuration file path 085 */ 086 public static void configure(String file) { 087 configure(new File(file)); 088 } 089 }