private void attachPassiveDbAppender( DbAppenderConfiguration appenderConfiguration, long timestamp ) { // create the new appender PassiveDbAppender attachedAppender = new PassiveDbAppender(ThreadsPerCaller.getCaller()); // calculate the time stamp offset, between the test executor and the agent attachedAppender.calculateTimeOffset(timestamp); attachedAppender.setAppenderConfig(appenderConfiguration); // use a default pattern, as we log in the db attachedAppender.setLayout(new PatternLayout("%c{2}: %m%n")); attachedAppender.activateOptions(); // attach the appender to the logging system Category log = Logger.getRootLogger(); log.setLevel(Level.toLevel(appenderConfiguration.getLoggingThreshold().toInt())); log.addAppender(attachedAppender); }
@SuppressWarnings("deprecation") @Test public void testAutoPopulate () { final TestClock tc = new TestClock ( 1234567890123L ); final EcompLayout layout = new EcompLayout (); MDC.put ( EcompFields.kBeginTimestampMs, Long.toString ( SaClock.now () ) ); tc.forward ( 60*1000L ); layout.format ( new LoggingEvent ( "foo.bar", Category.getRoot (), Priority.INFO, "foobar", null ) ); assertEquals ( "2009-02-13T23:31:30.123+00:00", MDC.get ( EcompFields.kBeginTimestamp ) ); assertEquals ( "2009-02-13T23:32:30.123+00:00", MDC.get ( EcompFields.kEndTimestamp ) ); assertEquals ( "60000", MDC.get ( EcompFields.kElapsedTimeMs ) ); }
/** * Creates the LoggingOutputStream to flush to the given Category. * * @param cat the Category to write to * * @param priority the Priority to use when writing to the Category * * @exception IllegalArgumentException * if cat == null or priority == null */ public LoggingOutputStream(Category cat, Priority priority) throws IllegalArgumentException { if (cat == null) { throw new IllegalArgumentException("cat == null"); } if (priority == null) { throw new IllegalArgumentException("priority == null"); } this.priority = priority; category = cat; bufLength = DEFAULT_BUFFER_LENGTH; buf = new byte[DEFAULT_BUFFER_LENGTH]; count = 0; }
/** * @throws Exception */ @Before public void setUp() throws Exception { new MockUp<Category>() { @SuppressWarnings("unused") @Mock public boolean isDebugEnabled() { return true; } @SuppressWarnings("unused") @Mock public boolean isEnabledFor(Priority level) { return true; } @SuppressWarnings("unused") @Mock public boolean isInfoEnabled() { return true; } }; logService = new StandardLogService(this.getClass().getName()); }
/** * Gets the hibernate session. * * @return the hibernate session * @throws UNISoNException * the UNI so n exception */ @SuppressWarnings("deprecation") public synchronized Session getHibernateSession() throws UNISoNException { HibernateHelper.logger.debug("getHibernateSession"); if (null == HibernateHelper.sessionFactory) { try { final Configuration config = this.getHibernateConfig(); // FIXME - couldn't stop the NoInitialContext warning so this // hack will stop it being displayed final Level level = Category.getRoot().getLevel(); Category.getRoot().setLevel(Level.FATAL); HibernateHelper.sessionFactory = config.buildSessionFactory(); Category.getRoot().setLevel(level); } catch (final Throwable e) { e.printStackTrace(); throw new UNISoNException("Failed to connect to DB", e); } } HibernateHelper.logger.debug("getHibernateSession"); return HibernateHelper.sessionFactory.openSession(); }
@Nullable public LogMessage addIdeFatalMessage(final IdeaLoggingEvent aEvent) { Object data = aEvent.getData(); final LogMessage message = data instanceof LogMessage ? (LogMessage)data : new LogMessage(aEvent); if (myIdeFatals.size() < MAX_POOL_SIZE_FOR_FATALS) { if (myFatalsGrouper.addToGroup(message)) { return message; } } else if (myIdeFatals.size() == MAX_POOL_SIZE_FOR_FATALS) { String msg = DiagnosticBundle.message("error.monitor.too.many.errors"); LogMessage tooMany = new LogMessage(new LoggingEvent(msg, Category.getRoot(), Priority.ERROR, null, new TooManyErrorsException())); myFatalsGrouper.addToGroup(tooMany); return tooMany; } return null; }
/** * Tests LoggingEvent.getLocationInfo() when no FQCN is specified. * See bug 41186. */ public void testLocationInfoNoFQCN() { Category root = Logger.getRootLogger(); Priority level = Level.INFO; LoggingEvent event = new LoggingEvent( null, root, 0L, level, "Hello, world.", null); LocationInfo info = event.getLocationInformation(); // // log4j 1.2 returns an object, its layout doesn't check for nulls. // log4j 1.3 returns a null. // assertNotNull(info); if (info != null) { assertEquals("?", info.getLineNumber()); assertEquals("?", info.getClassName()); assertEquals("?", info.getFileName()); assertEquals("?", info.getMethodName()); } }
public void test() { ListHandler listHandler = new ListHandler(); java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); root.addHandler(listHandler); root.setLevel(Level.FINEST); Logger log4jLogger = Logger.getLogger("a"); Category log4jCategory = Logger.getLogger("b"); int n = 0; log4jLogger.log(org.apache.log4j.Level.DEBUG, "hello" + (++n)); log4jCategory.log(org.apache.log4j.Level.DEBUG, "world" + (++n)); assertEquals(n, listHandler.list.size()); for (int i = 0; i < n; i++) { LogRecord logRecord = (LogRecord) listHandler.list.get(i); assertEquals("test", logRecord.getSourceMethodName()); } }
/** * * * @see javax.servlet.jsp.tagext.Tag#doStartTag() */ public int doEndTag() throws JspException { try { //pageContext.getOut().println(bodyContent.toString()); long end = System.currentTimeMillis(); Category.getInstance("timer").debug("time (ms): " + (end-start)); start = 0L; return EVAL_PAGE; } /* catch (IOException e) { throw new JspException(e); } */ catch (Exception e) { logger.error(e); if (e instanceof JspException) throw (JspException) e; throw new JspException(e); } finally { reset(); } }
@Test public void testAppendNormalEvent(){ Category cat=Category.getRoot(); long date=System.currentTimeMillis(); Level level=Level.DEBUG; String msg="this is a message"; String thread=Thread.currentThread().getName(); database.command(new OCommandSQL("delete from "+DB_TABLE_NAME)).execute(); LoggingEvent event= new LoggingEvent(null, cat,date , level, msg,thread , null, null, null, null); appender.append(event); appender.finalize(); List<ODocument> list=database.command(new OCommandSQL("select * from "+DB_TABLE_NAME+" limit 1")).execute(); ODocument result=list.get(0); Assert.assertEquals(new Date(date), result.field(EventMapper.TIMESTAMP)); Assert.assertEquals(level.toString(),result.field(EventMapper.LEVEL)); Assert.assertEquals(msg,result.field(EventMapper.MESSAGE)); Assert.assertEquals(cat.getName(),result.field(EventMapper.LOGGER_NAME)); Assert.assertEquals(thread,result.field(EventMapper.THREAD)); }
/** * initializes the log system using the logfile argument */ private void internalInit( String logfile ) throws Exception { /* * do it by our classname to avoid conflicting with anything else * that might be used... */ logger = Category.getInstance(this.getClass().getName()); logger.setAdditivity(false); /* * Priority is set for DEBUG becouse this implementation checks * log level. */ logger.setPriority(Priority.DEBUG); RollingFileAppender appender = new RollingFileAppender( new PatternLayout( "%d - %m%n"), logfile, true); appender.setMaxBackupIndex( 1 ); appender.setMaximumFileSize( 100000 ); logger.addAppender(appender); }
/** * Get all log classes names * * @return */ public static Map<String,Object> getLogClasses(){ SortedMap<String,Object> loggers = new TreeMap<String, Object>(); Map<String,Object> res = Objects.newHashMap( "level",LogManager.getRootLogger().getLevel().toString().toUpperCase(), "loggers",loggers ); Enumeration<Category> en = LogManager.getCurrentLoggers(); while(en.hasMoreElements()){ Category e = en.nextElement(); loggers.put(e.getName(),e.getEffectiveLevel().toString().toUpperCase()); } return res; }
public static Set<Appender> getAllAppendersIncludingParents(Logger logger) { Set<Appender> ret = new LinkedHashSet<Appender>(); for (Category category = logger; category != null; category = category.getParent()) { Enumeration<?> enumeration = category.getAllAppenders(); while (enumeration.hasMoreElements()) { // I have to use RTTI, since current version of log4j provides no // other alternative. Appender appender = (Appender) enumeration.nextElement(); ret.add(appender); } } return ret; }
@Test public void testLogLevel() throws Exception { Logger targetLogger = logTestSample.getTargetLogger(); assertEquals("egovframework.rte.fdl.logging.sample.LogTestSample", targetLogger.getName()); Category selectedCategory = targetLogger; // 대상 클래스 풀패키지명에 매칭되는 정의된 로거(Category)가 없으면 parent 를 따라 설정되므로 // 등록된 Category 는 level 이 정의되 있다는 가정하에 해당 Category 를 찾음 while (selectedCategory.getLevel() == null) { selectedCategory = selectedCategory.getParent(); } assertEquals("egovframework", selectedCategory.getName()); assertTrue(selectedCategory.isDebugEnabled()); assertEquals(Level.DEBUG, selectedCategory.getLevel()); assertTrue(!selectedCategory.getAdditivity()); // 현재 egovframework 로그 레벨이 log4j.xml 에 DEBUG 로 정의되 있으므로 // 해당 로거 정의(Category) 를 따르는 logTestSample 의 메서드를 실행하면 // DEBUG, INFO, WARN, ERROR, FATAL 에 대한 모든 로그가 출력될 것임. console 창에서 확인 logTestSample.executeSomeLogic(); }
public static boolean enableDebugLoggingIfRequired( org.apache.hadoop.conf.Configuration conf) { boolean result = false; try { Level desiredOraOopLoggingLevel = Level.toLevel(conf.get(OraOopConstants.ORAOOP_LOGGING_LEVEL), Level.INFO); Level sqoopLogLevel = Logger.getLogger(Sqoop.class.getName()).getParent().getLevel(); if (desiredOraOopLoggingLevel == Level.DEBUG || desiredOraOopLoggingLevel == Level.ALL || sqoopLogLevel == Level.DEBUG || sqoopLogLevel == Level.ALL) { Category oraOopLogger = Logger.getLogger(OraOopManagerFactory.class.getName()).getParent(); oraOopLogger.setLevel(Level.DEBUG); LOG.debug("Enabled OraOop debug logging."); result = true; conf.set(OraOopConstants.ORAOOP_LOGGING_LEVEL, Level.DEBUG.toString()); } } catch (Exception ex) { LOG.error(String.format( "Unable to determine whether debug logging should be enabled.\n%s", getFullExceptionMessage(ex))); } return result; }
/** * test TaskLogAppender */ @SuppressWarnings("deprecation") @Test (timeout=5000) public void testTaskLogAppender(){ TaskLogAppender appender= new TaskLogAppender(); System.setProperty(TaskLogAppender.TASKID_PROPERTY,"attempt_01_02_m03_04_001"); System.setProperty(TaskLogAppender.LOGSIZE_PROPERTY, "1003"); appender.activateOptions(); assertEquals(appender.getTaskId(), "attempt_01_02_m03_04_001"); assertEquals(appender.getTotalLogFileSize(),1000); assertEquals(appender.getIsCleanup(),false); // test writer Writer writer= new StringWriter(); appender.setWriter(writer); Layout layout = new PatternLayout("%-5p [%t]: %m%n"); appender.setLayout(layout); Category logger= Logger.getLogger(getClass().getName()); LoggingEvent event = new LoggingEvent("fqnOfCategoryClass", logger, Priority.INFO, "message", new Throwable()); appender.append(event); appender.flush() ; appender.close(); assertTrue(writer.toString().length()>0); // test cleanup should not changed appender= new TaskLogAppender(); appender.setIsCleanup(true); appender.activateOptions(); assertEquals(appender.getIsCleanup(),true); }
private static ArrayList<Appender> appenderHierarchy(final Logger logger) { ArrayList<Appender> _xblockexpression = null; { final ArrayList<Appender> appenders = CollectionLiterals.<Appender>newArrayList(); for (Category current = logger; (current != null); current = current.getParent()) { appenders.addAll(Collections.<Appender>list(current.getAllAppenders())); } _xblockexpression = appenders; } return _xblockexpression; }
@BeforeClass public static void setup() throws Exception { logger.debug("Logger repository before LoggerUtil.changeLoggersLevel() {}", LogManager.getLoggerRepository()); LoggerUtil.changeLoggersLevel(Maps.<String, String>newHashMap()); logger.debug("Logger repository after LoggerUtil.changeLoggersLevel() {}", LogManager.getLoggerRepository()); log4jLogger.setLevel(Level.TRACE); Category category = log4jLogger; while (category != null) { Enumeration appenders = category.getAllAppenders(); while (appenders.hasMoreElements()) { Object o = appenders.nextElement(); if (o instanceof AppenderSkeleton) { AppenderSkeleton appender = (AppenderSkeleton)o; if (!appenderLevelMap.containsKey(appender)) { appenderLevelMap.put(appender, appender.getThreshold()); appender.setThreshold(Level.INFO); } } } if (category.getAdditivity()) { category = category.getParent(); } else { category = null; } } }
@Test public void testParentLevel() { org.apache.log4j.Logger log4jLogger = LogManager.getLogger("com.datatorrent.stram.util.Unknown"); assertNull(log4jLogger.getLevel()); Category parent = log4jLogger.getParent(); while (parent.getLevel() == null) { parent = parent.getParent(); } assertSame(log4jLogger.getEffectiveLevel(), parent.getLevel()); }
protected void printOptions(PrintWriter out, Category cat) { Enumeration appenders = cat.getAllAppenders(); Level prio = cat.getLevel(); String appenderString = (prio == null ? "" : prio.toString()); while (appenders.hasMoreElements()) { Appender app = (Appender) appenders.nextElement(); String name; if ((name = (String) appenderNames.get(app)) == null) { // first assign name to the appender if ((name = app.getName()) == null || isGenAppName(name)) { name = genAppName(); } appenderNames.put(app, name); printOptions(out, app, "log4j.appender."+name); if (app.getLayout() != null) { printOptions(out, app.getLayout(), "log4j.appender."+name+".layout"); } } appenderString += ", " + name; } String catKey = (cat == Logger.getRootLogger()) ? "log4j.rootLogger" : "log4j.logger." + cat.getName(); if (appenderString != "") { out.println(catKey + "=" + appenderString); } if (!cat.getAdditivity() && cat != Logger.getRootLogger()) { out.println("log4j.additivity." + cat.getName() + "=false"); } }
/** * Tests LoggingEvent.fqnOfCategoryClass. */ public void testFQNOfCategoryClass() { Category root = Logger.getRootLogger(); Priority info = Level.INFO; String catName = Logger.class.toString(); LoggingEvent event = new LoggingEvent( catName, root, info, "Hello, world.", null); assertEquals(catName, event.fqnOfCategoryClass); }
/** * Tests LoggingEvent.level. * @deprecated */ public void testLevel() { Category root = Logger.getRootLogger(); Priority info = Level.INFO; String catName = Logger.class.toString(); LoggingEvent event = new LoggingEvent( catName, root, 0L, info, "Hello, world.", null); Priority error = Level.ERROR; event.level = error; assertEquals(Level.ERROR, event.level); }
public void testBug131() { ListHandler listHandler = new ListHandler(); java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); root.addHandler(listHandler); root.setLevel(Level.FINEST); Logger log4jLogger = Logger.getLogger("a"); Category log4jCategory = Logger.getLogger("b"); int n = 0; log4jLogger.trace("msg" + (n++)); log4jLogger.debug("msg" + (n++)); log4jLogger.info("msg" + (n++)); log4jLogger.warn("msg" + (n++)); log4jLogger.error("msg" + (n++)); log4jLogger.fatal("msg" + (n++)); log4jCategory.debug("msg" + (n++)); log4jCategory.info("msg" + (n++)); log4jCategory.warn("msg" + (n++)); log4jCategory.error("msg" + (n++)); log4jCategory.fatal("msg" + (n++)); assertEquals(n, listHandler.list.size()); for (int i = 0; i < n; i++) { LogRecord logRecord = (LogRecord) listHandler.list.get(i); assertEquals("testBug131", logRecord.getSourceMethodName()); } }
/** Instantiate a LoggingEvent from the supplied parameters. <p>Except {@link #timeStamp} all the other fields of <code>LoggingEvent</code> are filled when actually needed. <p> @param logger The logger generating this event. @param level The level of this event. @param message The message of this event. @param throwable The throwable of this event. */ public LogEvent(String fqnOfCategoryClass, Category logger, Priority level, Object message, Throwable throwable) { this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; this.categoryName = logger.getName(); this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = new ThrowableInformation(throwable); } timeStamp = System.currentTimeMillis(); }
/** Instantiate a LoggingEvent from the supplied parameters. <p>Except {@link #timeStamp} all the other fields of <code>LoggingEvent</code> are filled when actually needed. <p> @param logger The logger generating this event. @param timeStamp the timestamp of this logging event @param level The level of this event. @param message The message of this event. @param throwable The throwable of this event. */ public LogEvent(String fqnOfCategoryClass, Category logger, long timeStamp, Priority level, Object message, Throwable throwable) { this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; this.categoryName = logger.getName(); this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = new ThrowableInformation(throwable); } this.timeStamp = timeStamp; }
public void addAppenderEvent(Category logger, Appender appender) { log.debug("addAppenderEvent called: logger="+logger.getName()+ ", appender="+appender.getName()); Notification n = new Notification(ADD_APPENDER+logger.getName(), this, 0); n.setUserData(appender); log.debug("sending notification."); nbs.sendNotification(n); }
/** Instantiate a LoggingEvent from the supplied parameters. <p>Except {@link #timeStamp} all the other fields of <code>LoggingEvent</code> are filled when actually needed. <p> @param logger The logger generating this event. @param level The level of this event. @param message The message of this event. @param throwable The throwable of this event. */ public LoggingEvent(String fqnOfCategoryClass, Category logger, Priority level, Object message, Throwable throwable) { this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; this.categoryName = logger.getName(); this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = new ThrowableInformation(throwable, logger); } timeStamp = System.currentTimeMillis(); }
/** Instantiate a LoggingEvent from the supplied parameters. <p>Except {@link #timeStamp} all the other fields of <code>LoggingEvent</code> are filled when actually needed. <p> @param logger The logger generating this event. @param timeStamp the timestamp of this logging event @param level The level of this event. @param message The message of this event. @param throwable The throwable of this event. */ public LoggingEvent(String fqnOfCategoryClass, Category logger, long timeStamp, Priority level, Object message, Throwable throwable) { this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; this.categoryName = logger.getName(); this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = new ThrowableInformation(throwable, logger); } this.timeStamp = timeStamp; }
/** Create new instance. @since 1.2.15 @param fqnOfCategoryClass Fully qualified class name of Logger implementation. @param logger The logger generating this event. @param timeStamp the timestamp of this logging event @param level The level of this event. @param message The message of this event. @param threadName thread name @param throwable The throwable of this event. @param ndc Nested diagnostic context @param info Location info @param properties MDC properties */ public LoggingEvent(final String fqnOfCategoryClass, final Category logger, final long timeStamp, final Level level, final Object message, final String threadName, final ThrowableInformation throwable, final String ndc, final LocationInfo info, final java.util.Map properties) { super(); this.fqnOfCategoryClass = fqnOfCategoryClass; this.logger = logger; if (logger != null) { categoryName = logger.getName(); } else { categoryName = null; } this.level = level; this.message = message; if(throwable != null) { this.throwableInfo = throwable; } this.timeStamp = timeStamp; this.threadName = threadName; ndcLookupRequired = false; this.ndc = ndc; this.locationInfo = info; mdcCopyLookupRequired = false; if (properties != null) { mdcCopy = new java.util.Hashtable(properties); } }
/** * @since 1.2.15 */ protected void printOptions(PrintWriter out, Category cat) { Enumeration appenders = cat.getAllAppenders(); Level prio = cat.getLevel(); String appenderString = (prio == null ? "" : prio.toString()); while (appenders.hasMoreElements()) { Appender app = (Appender) appenders.nextElement(); String name; if ((name = (String) appenderNames.get(app)) == null) { // first assign name to the appender if ((name = app.getName()) == null || isGenAppName(name)) { name = genAppName(); } appenderNames.put(app, name); printOptions(out, app, "log4j.appender."+name); if (app.getLayout() != null) { printOptions(out, app.getLayout(), "log4j.appender."+name+".layout"); } } appenderString += ", " + name; } String catKey = (cat == Logger.getRootLogger()) ? "log4j.rootLogger" : "log4j.logger." + cat.getName(); if (appenderString != "") { out.println(catKey + "=" + appenderString); } if (!cat.getAdditivity() && cat != Logger.getRootLogger()) { out.println("log4j.additivity." + cat.getName() + "=false"); } }
private LoggingEvent parseMatcher(String event, Matcher m, String messageAdd, List<String> causes) throws ParseException{ LoggingEvent e = null; String thread = m.group(2); SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss,SSS"); sdf.setTimeZone(TimeZone.getTimeZone("Etc/GMT+3")); long timestamp = sdf.parse(m.group(3)).getTime(); String loggerFqn = m.group(5); Category cat = new EventCategory(loggerFqn); String level = m.group(4); Level prio = null; messageAdd = messageAdd + validateCauses(causes); switch(level){ case "FATAL": prio = Level.FATAL; break; case "ERROR":prio = Level.ERROR; break; case "WARN":prio = Level.WARN; break; case "INFO":prio = Level.INFO; break; case "DEBUG":prio = Level.DEBUG; break; case "TRACE":prio = Level.TRACE; break; } String message = m.group(6)+messageAdd; e = new LoggingEvent(loggerFqn, cat, timestamp, prio, message, thread, new ThrowableInformation(causes.toArray(new String[causes.size()])), (String)null, (LocationInfo)null, null); events++; System.out.println("Parsed "+events+" event(s). Last event on "+m.group(3)); return e; }