Example usage for java.util.logging LogRecord LogRecord

List of usage examples for java.util.logging LogRecord LogRecord

Introduction

In this page you can find the example usage for java.util.logging LogRecord LogRecord.

Prototype

public LogRecord(Level level, String msg) 

Source Link

Document

Construct a LogRecord with the given level and message values.

Usage

From source file:org.apache.tomee.jul.handler.rotating.LocalFileHandlerTest.java

@Test
public void logAndRotate() throws IOException {
    final File out = new File("target/LocalFileHandlerTest/logs/");
    if (out.exists()) {
        for (final File file : asList(out.listFiles(new FileFilter() {
            @Override//w  w  w .ja v  a2s  .com
            public boolean accept(final File pathname) {
                return pathname.getName().startsWith("test");
            }
        }))) {
            if (!file.delete()) {
                file.deleteOnExit();
            }
        }
    }

    final AtomicReference<String> today = new AtomicReference<>();
    final Map<String, String> config = new HashMap<>();

    // initial config
    today.set("day1");
    config.put("filenamePattern", "target/LocalFileHandlerTest/logs/test.%s.%d.log");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");
    config.put("formatter", MessageOnlyFormatter.class.getName());

    final LocalFileHandler handler = new LocalFileHandler() {
        @Override
        protected String currentDate() {
            return today.get();
        }

        @Override
        protected String getProperty(final String name, final String defaultValue) {
            final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
            return s != null ? s : defaultValue;
        }
    };

    final String string10chars = "abcdefghij";
    final int iterations = 950;
    for (int i = 0; i < iterations; i++) {
        handler.publish(new LogRecord(Level.INFO, string10chars));
    }

    final File[] logFiles = out.listFiles(new FileFilter() {
        @Override
        public boolean accept(final File pathname) {
            return pathname.getName().startsWith("test");
        }
    });
    final Set<String> logFilesNames = new HashSet<>();
    for (final File f : logFiles) {
        logFilesNames.add(f.getName());
    }
    assertEquals(2, logFiles.length);
    assertEquals(new HashSet<>(asList("test.day1.0.log", "test.day1.1.log")), logFilesNames);

    try (final InputStream is = new FileInputStream(new File(out, "test.day1.1.log"))) {
        final List<String> lines = IOUtils.readLines(is);
        assertEquals(19, lines.size());
        assertEquals(string10chars, lines.iterator().next());
    }

    final long firstFileLen = new File(out, "test.day1.0.log").length();
    assertTrue(firstFileLen >= 1024 * 10 && firstFileLen < 1024 * 10 + (1 + string10chars.getBytes().length));

    // now change of day
    today.set("day2");
    try { // ensure we tets the date
        Thread.sleep(1500);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }
    handler.publish(new LogRecord(Level.INFO, string10chars));
    assertTrue(new File(out, "test.day2.0.log").exists());

    handler.close();
}

From source file:jenkins.security.plugins.ldap.FromUserRecordLDAPGroupMembershipStrategy.java

@Override
public GrantedAuthority[] getGrantedAuthorities(LdapUserDetails ldapUser) {
    List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
    Attributes attributes = ldapUser.getAttributes();
    final String attributeName = getAttributeName();
    Attribute attribute = attributes == null ? null : attributes.get(attributeName);
    if (attribute != null) {
        try {/* w ww  . j  a  v a2  s  .co  m*/
            for (Object value : Collections.list(attribute.getAll())) {
                String groupName = String.valueOf(value);
                try {
                    LdapName dn = new LdapName(groupName);
                    groupName = String.valueOf(dn.getRdn(dn.size() - 1).getValue());
                } catch (InvalidNameException e) {
                    LOGGER.log(Level.FINEST, "Expected a Group DN but found: {0}", groupName);
                }
                result.add(new GrantedAuthorityImpl(groupName));
            }
        } catch (NamingException e) {
            LogRecord lr = new LogRecord(Level.FINE,
                    "Failed to retrieve member of attribute ({0}) from LDAP user details");
            lr.setThrown(e);
            lr.setParameters(new Object[] { attributeName });
            LOGGER.log(lr);
        }

    }
    return result.toArray(new GrantedAuthority[result.size()]);
}

From source file:org.apache.tomee.jul.handler.rotating.ArchivingTest.java

@Test
public void logAndRotate() throws IOException, NoSuchMethodException {
    clean("target/ArchivingTest-" + format + "/logs");

    final AtomicReference<String> today = new AtomicReference<>();
    final Map<String, String> config = new HashMap<>();

    // initial config
    today.set("2015-09-01");
    config.put("filenamePattern", "target/ArchivingTest-" + format + "/logs/test.%s.%d.log");
    config.put("archiveDirectory", "target/ArchivingTest-" + format + "/logs/archives");
    config.put("archiveFormat", format);
    config.put("archiveOlderThan", "1 s");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");

    final LocalFileHandler handler = new LocalFileHandler() {
        @Override//  w w  w.  j av  a 2  s . c om
        protected String currentDate() {
            return today.get();
        }

        @Override
        protected String getProperty(final String name, final String defaultValue) {
            final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
            return s != null ? s : defaultValue;
        }
    };

    final String string10chars = "abcdefghij";
    final int iterations = 950;
    for (int i = 0; i < iterations; i++) {
        handler.publish(new LogRecord(Level.INFO, string10chars));
    }

    today.set("2015-09-02");
    try { // ensure we test the date
        Thread.sleep(2000);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }
    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving
    handler.close();

    withRetry(10, 3, new Runnable() {
        @Override
        public void run() {
            final File logGzip = new File(
                    "target/ArchivingTest-" + format + "/logs/archives/test.2015-09-01.0.log." + format);
            assertTrue(logGzip.getAbsolutePath(), logGzip.isFile());
        }
    });
    // note: size depends on the date so just use a > min
    if ("gzip".equals(format)) {
        try (final GZIPInputStream gis = new GZIPInputStream(
                new FileInputStream("target/ArchivingTest-gzip/logs/archives/test.2015-09-01.0.log.gzip"))) {
            final String content = IOUtils.toString(gis);
            assertTrue(
                    content.contains(Level.INFO.getLocalizedName() + ": abcdefghij" + System.lineSeparator()));
            assertTrue(content.length() > 10000);
        }
    } else {
        try (final ZipInputStream zis = new ZipInputStream(
                new FileInputStream("target/ArchivingTest-zip/logs/archives/test.2015-09-01.0.log.zip"))) {
            assertEquals("test.2015-09-01.0.log", zis.getNextEntry().getName());
            final String content = IOUtils.toString(zis);
            assertTrue(content,
                    content.contains(Level.INFO.getLocalizedName() + ": abcdefghij" + System.lineSeparator())); // INFO or INFOS
            assertTrue(content, content.length() > 10000);
            assertNull(zis.getNextEntry());
        }
    }
}

From source file:fr.opensagres.xdocreport.core.logging.LogUtils.java

private static void doLog(Logger log, Level level, String msg, Throwable t) {
    LogRecord record = new LogRecord(level, msg);

    record.setLoggerName(log.getName());
    record.setResourceBundleName(log.getResourceBundleName());
    record.setResourceBundle(log.getResourceBundle());

    if (t != null) {
        record.setThrown(t);//from ww  w . j a  v  a  2s.  c  o m
    }

    // try to get the right class name/method name - just trace
    // back the stack till we get out of this class
    StackTraceElement stack[] = (new Throwable()).getStackTrace();
    String cname = LogUtils.class.getName();
    for (int x = 0; x < stack.length; x++) {
        StackTraceElement frame = stack[x];
        if (!frame.getClassName().equals(cname)) {
            record.setSourceClassName(frame.getClassName());
            record.setSourceMethodName(frame.getMethodName());
            break;
        }
    }
    log.log(record);
}

From source file:com.cloudbees.plugins.credentials.impl.CertificateCredentialsImpl.java

/**
 * Returns the {@link KeyStore} containing the certificate.
 *
 * @return the {@link KeyStore} containing the certificate.
 *///from  ww w .j av  a 2  s .c o m
@NonNull
public synchronized KeyStore getKeyStore() {
    long lastModified = keyStoreSource.getKeyStoreLastModified();
    if (keyStore == null || keyStoreLastModified < lastModified) {
        KeyStore keyStore;
        try {
            keyStore = KeyStore.getInstance("PKCS12");
        } catch (KeyStoreException e) {
            throw new IllegalStateException("PKCS12 is a keystore type per the JLS spec", e);
        }
        try {
            keyStore.load(new ByteArrayInputStream(keyStoreSource.getKeyStoreBytes()), toCharArray(password));
        } catch (CertificateException e) {
            LogRecord lr = new LogRecord(Level.WARNING, "Credentials ID {0}: Could not load keystore from {1}");
            lr.setParameters(new Object[] { getId(), keyStoreSource });
            lr.setThrown(e);
            LOGGER.log(lr);
        } catch (NoSuchAlgorithmException e) {
            LogRecord lr = new LogRecord(Level.WARNING, "Credentials ID {0}: Could not load keystore from {1}");
            lr.setParameters(new Object[] { getId(), keyStoreSource });
            lr.setThrown(e);
            LOGGER.log(lr);
        } catch (IOException e) {
            LogRecord lr = new LogRecord(Level.WARNING, "Credentials ID {0}: Could not load keystore from {1}");
            lr.setParameters(new Object[] { getId(), keyStoreSource });
            lr.setThrown(e);
            LOGGER.log(lr);
        }
        this.keyStore = keyStore;
        this.keyStoreLastModified = lastModified;
    }
    return keyStore;
}

From source file:org.apache.tomee.jul.handler.rotating.ArchivingTest.java

@SuppressWarnings("unchecked")
@Test//  ww  w.  j  a v  a  2 s  .c o  m
public void logAndRotateAndPurge() throws Exception {
    clean("target/ArchivingTestPurge-" + format + "/logs");

    final AtomicReference<String> today = new AtomicReference<>();
    final Map<String, String> config = new HashMap<>();

    // initial config
    today.set("2015-09-01");
    config.put("filenamePattern", "target/ArchivingTestPurge-" + format + "/logs/test.%s.%d.log");
    config.put("archiveDirectory", "target/ArchivingTestPurge-" + format + "/logs/archives");
    config.put("archiveFormat", format);
    config.put("archiveOlderThan", "1 s");
    config.put("purgeOlderThan", "2 s");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");

    final LocalFileHandler handler = new LocalFileHandler() {
        @Override
        protected String currentDate() {
            return today.get();
        }

        @Override
        protected String getProperty(final String name, final String defaultValue) {
            final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
            return s != null ? s : defaultValue;
        }
    };

    final String string10chars = "abcdefghij";
    final int iterations = 950;
    for (int i = 0; i < iterations; i++) {
        handler.publish(new LogRecord(Level.INFO, string10chars));
    }

    today.set("2015-09-02");
    try {
        Thread.sleep(2000);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }

    final File logArchive = new File(
            "target/ArchivingTestPurge-" + format + "/logs/archives/test.2015-09-01.0.log." + format);
    final File parentFile = logArchive.getParentFile();
    if (!parentFile.exists() && !parentFile.mkdirs()) {
        Assert.fail("Unable to create: " + parentFile);
    }
    final Path dir = parentFile.toPath();
    final WatchService watcher = FileSystems.getDefault().newWatchService();
    final WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);

    latch.set(new CountDownLatch(1));
    watch(key);

    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving

    assertTrue("Failed to get archived log", latch.get().await(20, TimeUnit.SECONDS));
    final WatchEvent<?> watchEvent = lastEvent.get();

    assertTrue(StandardWatchEventKinds.ENTRY_CREATE.equals(watchEvent.kind())
            || StandardWatchEventKinds.ENTRY_MODIFY.equals(watchEvent.kind()));

    final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;

    final String io = ev.context().toString();
    assertTrue(io.startsWith("test.2015-09-01.") && io.endsWith(format));

    today.set("2015-09-03");
    try {
        Thread.sleep(2500);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }

    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the purging
    handler.close();
    withRetry(10, 2, new Runnable() {
        @Override
        public void run() {
            assertFalse(logArchive.getAbsolutePath() + " was purged", logArchive.exists());
        }
    });
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/** Called after VirtMus has started up.
 * Should only be called once per startup, and after we've detected the new
 * and old app version (if this was an upgrade).
 *///from  www  . ja v a2 s  .  c o m
public void startedUp() {
    int launch = pref.getInt(Options.OptStartCounter, 1);
    pref.putInt(Options.OptStartCounter, launch + 1);

    UploadStats upload = UploadStats.valueOf(pref.get(Options.OptUploadStats, UploadStats.Unknown.name()));

    // Only ask the 2nd time the user starts up the app
    if (launch > 1) {
        if (upload == UploadStats.Unknown || (upload == UploadStats.Maybe && (launch % 10 == 0))
                || (upload == UploadStats.No && (launch % 100 == 0))) {

            UploadStats newUpload = promptUser();
            if (newUpload != upload) {
                pref.put(Options.OptUploadStats, newUpload.name());
                upload = newUpload;
            }
        }
    }

    long installId = MainApp.getInstallId();
    String prevVersion = pref.get(Options.OptPrevAppVersion, "0.00");
    if (pref.getBoolean(Options.OptCheckVersion, true)) {
        StatsLogger.checkForNewVersion(installId, prevVersion, upload);
    }

    if (upload != UploadStats.No) {

        LogRecord rec = new LogRecord(Level.INFO, "VirtMus Version");
        rec.setParameters(new Object[] { MainApp.VERSION, prevVersion, installId });
        statsLog.log(rec);

        StatsCollector.logStartup(statsLog);
        // TODO: Log uptime, etc...
    }

    if (upload == UploadStats.Yes) {
        uploadLogs();
    }
}

From source file:fr.cnes.sitools.security.filter.SecurityFilter.java

/**
 * Log./* ww  w. ja v a  2 s .  c o m*/
 * 
 * @param request
 *          the request
 * @param response
 *          the response
 * @param ip
 *          the ip address
 */
private void log(Request request, Response response, String ip) {

    String message = "Request to: " + request.getResourceRef().getPath() + " forbiden, IP address: " + ip
            + " is out of Intranet domain";

    LogRecord record = new LogRecord(Level.WARNING, message);
    response.getAttributes().put("LOG_RECORD", record);

}

From source file:com.l2jfree.gameserver.communitybbs.Manager.RegionBBSManager.java

@Override
public void parsewrite(String ar1, String ar2, String ar3, String ar4, String ar5, L2Player activeChar) {
    if (activeChar == null)
        return;//from w w w  .j  a v a  2  s.c om

    if (ar1.equals("PM")) {
        final L2TextBuilder htmlCode = L2TextBuilder.newInstance();
        htmlCode.append("<html><body><br>");
        htmlCode.append(
                "<table border=0><tr><td FIXWIDTH=15></td><td align=center>L2J Community Board<img src=\"sek.cbui355\" width=610 height=1></td></tr><tr><td FIXWIDTH=15></td><td>");

        try {

            L2Player receiver = L2World.getInstance().getPlayer(ar2);
            if (receiver == null) {
                htmlCode.append(
                        "Player not found!<br><button value=\"Back\" action=\"bypass _bbsloc;playerinfo;")
                        .append(ar2).append("\" width=40 height=15 back=\"sek.cbui94\" fore=\"sek.cbui92\">");
                htmlCode.append("</td></tr></table></body></html>");
                separateAndSend(htmlCode, activeChar);
                return;
            }
            if (Config.JAIL_DISABLE_CHAT && receiver.isInJail()) {
                activeChar.sendMessage("Player is in jail.");
                return;
            }
            if (receiver.isChatBanned()) {
                activeChar.sendMessage("Player is chat banned.");
                return;
            }
            if (activeChar.isInJail() && Config.JAIL_DISABLE_CHAT) {
                activeChar.sendMessage("You cannot chat while in jail.");
                return;
            }

            if (Config.LOG_CHAT) {
                LogRecord record = new LogRecord(Level.INFO, ar3);
                record.setLoggerName("chat");
                record.setParameters(new Object[] { "TELL",
                        "[" + activeChar.getName() + " to " + receiver.getName() + "]" });
                _logChat.log(record);
            }
            CreatureSay cs = new CreatureSay(activeChar.getObjectId(), SystemChatChannelId.Chat_Tell,
                    activeChar.getName(), ar3);
            if (!BlockList.isBlocked(receiver, activeChar)) {
                if (!receiver.getMessageRefusal()) {
                    receiver.sendPacket(cs);
                    activeChar.sendPacket(new CreatureSay(activeChar.getObjectId(),
                            SystemChatChannelId.Chat_Tell, "->" + receiver.getName(), ar3));
                    htmlCode.append(
                            "Message Sent<br><button value=\"Back\" action=\"bypass _bbsloc;playerinfo;")
                            .append(receiver.getName())
                            .append("\" width=40 height=15 back=\"sek.cbui94\" fore=\"sek.cbui92\">");
                    htmlCode.append("</td></tr></table></body></html>");
                    separateAndSend(htmlCode, activeChar);
                } else {
                    activeChar.sendPacket(SystemMessageId.THE_PERSON_IS_IN_MESSAGE_REFUSAL_MODE);
                    parsecmd("_bbsloc;playerinfo;" + receiver.getName(), activeChar);
                }
            } else {
                SystemMessage sm = new SystemMessage(SystemMessageId.S1_IS_NOT_ONLINE);
                sm.addString(receiver.getName());
                activeChar.sendPacket(sm);
                sm = null;
            }
        } catch (StringIndexOutOfBoundsException e) {
            // ignore
        }
    } else {
        notImplementedYet(activeChar, ar1);
    }
}

From source file:org.jretty.log.Jdk14Logger.java

/**
 * Log the message at the specified level with the specified throwable if any. This method creates a LogRecord and fills in caller date before calling this
 * instance's JDK14 logger.//from   ww  w. j a  va  2  s. co  m
 */
private void log(String callerFQCN, Level level, String msg, Throwable t) {
    // millis and thread are filled by the constructor
    LogRecord record = new LogRecord(level, msg);
    record.setLoggerName(loggerName);
    record.setThrown(t);
    fillCallerData(callerFQCN, record);
    log.log(record);
}