package net.sourceforge.javautil.common.logging;
import java.io.PrintWriter;
import net.sourceforge.javautil.common.context.Context;
import net.sourceforge.javautil.common.logging.standard.LoggingFrameworkWriter;
/**
 * The context in which {@link ILoggingFramework}'s are accessed.
 * 
 * @author elponderador
 * @author $Author$
 * @version $Id$
 */
public class LoggingContext extends Context {
  
  /**
   * Facility for using class names for logger names.
   */
  public static LoggerContextual getContextualLogger (Class clazz) {
    return getContextualLogger(clazz.getName());
  }
  
  /**
   * @param name The name of the logger 
   * @return A new contextual logger instance
   */
  public static LoggerContextual getContextualLogger (String name) {
    return new LoggerContextual(name);
  }
  
  /**
   * @return The logging context related to the current thread
   */
  public static LoggingContext getInstance () {
    LoggingContext context = Context.get(LoggingContext.class);
    if (context == null) {
      synchronized (LoggingContext.class) {
        context = Context.get(LoggingContext.class);
        if (context == null) {
          (context = new LoggingContext(new LoggingFrameworkWriter(new PrintWriter(System.out, true)))).setGlobal();
        }
      }
    }
    return context;
  }
  
  /**
   * @param name The name of the logger
   * @return The logger associated with the name
   */
  public static ILogger getLogger (String name) { return getInstance().getNamedLogger(name); }
  
  /**
   * @param clazz The clazz for which a logger is desired
   * @return The logger for this class
   */
  public static ILogger getLogger (Class clazz) { return getInstance().getClassLogger(clazz); }
  protected final ILoggingFramework<?> framework;
  
  public LoggingContext(ILoggingFramework<?> framework) {
    this.framework = framework;
  }
  
  /**
   * @return The framework for this context
   */
  public ILoggingFramework<?> getFramework () { return framework; }
  
  /**
   * @param name The name of the logger
   * @return The logger associated with the name
   */
  public ILogger getNamedLogger (String name) { return framework.getLogger(name); }
  
  /**
   * @param clazz The clazz for which a logger is desired
   * @return The logger associated with this class
   */
  public ILogger getClassLogger (Class clazz) { return getNamedLogger(clazz.getName()); }
}