001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.rolling;
015
016import org.junit.After;
017import org.junit.Before;
018import org.junit.Test;
019
020import ch.qos.logback.classic.ClassicTestConstants;
021import ch.qos.logback.classic.Logger;
022import ch.qos.logback.classic.LoggerContext;
023import ch.qos.logback.classic.joran.JoranConfigurator;
024import ch.qos.logback.core.joran.spi.JoranException;
025import ch.qos.logback.core.rolling.testUtil.ScaffoldingForRollingTests;
026import ch.qos.logback.core.testUtil.CoreTestConstants;
027import ch.qos.logback.core.testUtil.RandomUtil;
028import ch.qos.logback.core.testUtil.StatusChecker;
029import ch.qos.logback.core.util.CachingDateFormatter;
030
031/**
032 * Test that we can create time-stamped log files with the help of
033 * the <timestamp> element in configuration files.
034 * 
035 * @author Ceki Gülcü
036 *
037 */
038public class UniqueFileTest {
039    static String UNIK_DIFF = "UNIK_DIFF";
040
041    LoggerContext lc = new LoggerContext();
042    StatusChecker sc = new StatusChecker(lc);
043    Logger logger = lc.getLogger(this.getClass());
044    int diff = RandomUtil.getPositiveInt() % 1000;
045    String diffAsStr = Integer.toString(diff);
046
047    @Before
048    public void setUp() {
049        System.setProperty(UNIK_DIFF, diffAsStr);
050    }
051
052    @After
053    public void tearDown() {
054        System.clearProperty(UNIK_DIFF);
055    }
056
057    void loadConfig(String confifFile) throws JoranException {
058        JoranConfigurator jc = new JoranConfigurator();
059        jc.setContext(lc);
060        jc.doConfigure(confifFile);
061    }
062
063    @Test
064    public void basic() throws Exception {
065        loadConfig(ClassicTestConstants.JORAN_INPUT_PREFIX + "unique.xml");
066        CachingDateFormatter sdf = new CachingDateFormatter("yyyyMMdd'T'HHmm");
067        String timestamp = sdf.format(System.currentTimeMillis());
068
069        sc.assertIsErrorFree();
070
071        Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
072        root.info("hello");
073
074        ScaffoldingForRollingTests.existenceCheck(CoreTestConstants.OUTPUT_DIR_PREFIX + "UNIK_" + timestamp + diffAsStr + "log.txt");
075    }
076}