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 import java.lang.reflect.Method; 009 010 import org.slf4j.Logger; 011 import org.slf4j.LoggerFactory; 012 013 014 /** 015 * Configure loggers. 016 * 017 * @author Bartosz Firyn (SarXos) 018 */ 019 public class WebcamLogConfigurator { 020 021 /** 022 * Logger instance. 023 */ 024 private static final Logger LOG = LoggerFactory.getLogger(WebcamLogConfigurator.class); 025 026 /** 027 * Configure SLF4J. 028 * 029 * @param is input stream to logback configuration xml 030 */ 031 public static void configure(InputStream is) { 032 033 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 034 035 try { 036 037 String[] names = { 038 "ch.qos.logback.classic.LoggerContext", 039 "ch.qos.logback.classic.joran.JoranConfigurator", 040 }; 041 042 for (String name : names) { 043 Class.forName(name, false, cl); 044 } 045 046 Object context = LoggerFactory.getILoggerFactory(); 047 048 Class<?> cfgc = Class.forName("ch.qos.logback.classic.joran.JoranConfigurator"); 049 Object configurator = cfgc.newInstance(); 050 051 Method setContext = cfgc.getMethod("setContext"); 052 setContext.invoke(configurator, context); 053 054 Method reset = context.getClass().getMethod("reset"); 055 reset.invoke(context, new Object[0]); 056 057 Method doConfigure = cfgc.getMethod("doConfigure"); 058 doConfigure.invoke(configurator, is); 059 060 } catch (ClassNotFoundException e) { 061 System.err.println("WLogC: Logback JARs are missing in classpath"); 062 } catch (Exception e) { 063 LOG.error("Joran configuration exception", e); 064 } 065 } 066 067 /** 068 * Configure SLF4J. 069 * 070 * @param file logback configuration file 071 */ 072 public static void configure(File file) { 073 FileInputStream fis = null; 074 try { 075 fis = new FileInputStream(file); 076 configure(fis); 077 } catch (FileNotFoundException e) { 078 LOG.error("File not found " + file, e); 079 e.printStackTrace(); 080 } finally { 081 if (fis != null) { 082 try { 083 fis.close(); 084 } catch (IOException e) { 085 LOG.error("Cannot close file " + file, e); 086 e.printStackTrace(); 087 } 088 } 089 } 090 } 091 092 /** 093 * Configure SLF4J. 094 * 095 * @param file logback configuration file path 096 */ 097 public static void configure(String file) { 098 configure(new File(file)); 099 } 100 }