Example usage for java.util.logging Logger log

List of usage examples for java.util.logging Logger log

Introduction

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

Prototype

public void log(Level level, Throwable thrown, Supplier<String> msgSupplier) 

Source Link

Document

Log a lazily constructed message, with associated Throwable information.

Usage

From source file:Main.java

public static void main(String[] argv) {
    Logger logger = Logger.getLogger("com.mycompany.MyClass");
    try {//  w ww  . java  2  s.  c om
        throw new IOException();
    } catch (Throwable e) {
        logger.log(Level.SEVERE, "Uncaught exception", e);
    }
    Exception ex = new IllegalStateException();
    logger.throwing("Main class", "myMethod", ex);
}

From source file:Person.java

public static void main(String args[]) {
    Logger logger = Logger.getLogger("your.logging");
    AgeFilter filter = new AgeFilter();
    logger.setFilter(filter);/*from w ww  .  j  av  a 2  s.  c  o m*/
    Person person = new Person("YourName", 32);
    logger.log(Level.INFO, "Person has age " + person.getAge(), person);
}

From source file:DaytimeServer.java

public static void main(String args[]) {
    try { // Handle startup exceptions at the end of this block
        // Get an encoder for converting strings to bytes
        CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();

        // Allow an alternative port for testing with non-root accounts
        int port = 13; // RFC867 specifies this port.
        if (args.length > 0)
            port = Integer.parseInt(args[0]);

        // The port we'll listen on
        SocketAddress localport = new InetSocketAddress(port);

        // Create and bind a tcp channel to listen for connections on.
        ServerSocketChannel tcpserver = ServerSocketChannel.open();
        tcpserver.socket().bind(localport);

        // Also create and bind a DatagramChannel to listen on.
        DatagramChannel udpserver = DatagramChannel.open();
        udpserver.socket().bind(localport);

        // Specify non-blocking mode for both channels, since our
        // Selector object will be doing the blocking for us.
        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        // The Selector object is what allows us to block while waiting
        // for activity on either of the two channels.
        Selector selector = Selector.open();

        // Register the channels with the selector, and specify what
        // conditions (a connection ready to accept, a datagram ready
        // to read) we'd like the Selector to wake up for.
        // These methods return SelectionKey objects, which we don't
        // need to retain in this example.
        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        // This is an empty byte buffer to receive emtpy datagrams with.
        // If a datagram overflows the receive buffer size, the extra bytes
        // are automatically discarded, so we don't have to worry about
        // buffer overflow attacks here.
        ByteBuffer receiveBuffer = ByteBuffer.allocate(0);

        // Now loop forever, processing client connections
        for (;;) {
            try { // Handle per-connection problems below
                // Wait for a client to connect
                selector.select();//from   w  ww .j  a v a 2s  . c om

                // If we get here, a client has probably connected, so
                // put our response into a ByteBuffer.
                String date = new java.util.Date().toString() + "\r\n";
                ByteBuffer response = encoder.encode(CharBuffer.wrap(date));

                // Get the SelectionKey objects for the channels that have
                // activity on them. These are the keys returned by the
                // register() methods above. They are returned in a
                // java.util.Set.
                Set keys = selector.selectedKeys();

                // Iterate through the Set of keys.
                for (Iterator i = keys.iterator(); i.hasNext();) {
                    // Get a key from the set, and remove it from the set
                    SelectionKey key = (SelectionKey) i.next();
                    i.remove();

                    // Get the channel associated with the key
                    Channel c = (Channel) key.channel();

                    // Now test the key and the channel to find out
                    // whether something happend on the TCP or UDP channel
                    if (key.isAcceptable() && c == tcpserver) {
                        // A client has attempted to connect via TCP.
                        // Accept the connection now.
                        SocketChannel client = tcpserver.accept();
                        // If we accepted the connection successfully,
                        // the send our respone back to the client.
                        if (client != null) {
                            client.write(response); // send respone
                            client.close(); // close connection
                        }
                    } else if (key.isReadable() && c == udpserver) {
                        // A UDP datagram is waiting. Receive it now,
                        // noting the address it was sent from.
                        SocketAddress clientAddress = udpserver.receive(receiveBuffer);
                        // If we got the datagram successfully, send
                        // the date and time in a response packet.
                        if (clientAddress != null)
                            udpserver.send(response, clientAddress);
                    }
                }
            } catch (java.io.IOException e) {
                // This is a (hopefully transient) problem with a single
                // connection: we log the error, but continue running.
                // We use our classname for the logger so that a sysadmin
                // can configure logging for this server independently
                // of other programs.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.WARNING, "IOException in DaytimeServer", e);
            } catch (Throwable t) {
                // If anything else goes wrong (out of memory, for example)
                // then log the problem and exit.
                Logger l = Logger.getLogger(DaytimeServer.class.getName());
                l.log(Level.SEVERE, "FATAL error in DaytimeServer", t);
                System.exit(1);
            }
        }
    } catch (Exception e) {
        // This is a startup error: there is no need to log it;
        // just print a message and exit
        System.err.println(e);
        System.exit(1);
    }
}

From source file:bookChapter.theoretical.AnalyzeTheoreticalMSMSCalculation.java

/**
 *
 * @param args//from ww w  .j  a  va 2s  .  c  om
 * @throws IOException
 * @throws FileNotFoundException
 * @throws ClassNotFoundException
 * @throws InterruptedException
 * @throws MzMLUnmarshallerException
 */
public static void main(String[] args) throws IOException, FileNotFoundException, ClassNotFoundException,
        IOException, InterruptedException, MzMLUnmarshallerException {
    Logger l = Logger.getLogger("AnalyzeTheoreticalMSMSCalculation");
    Date date = Calendar.getInstance().getTime();
    DateFormat formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    String now = formatter.format(date);
    l.log(Level.INFO, "Calculation starts at {0}", now);
    double precursorTolerance = ConfigHolder.getInstance().getDouble("precursor.tolerance"),
            fragmentTolerance = ConfigHolder.getInstance().getDouble("fragment.tolerance");
    String databaseName = ConfigHolder.getInstance().getString("database.name"),
            spectraName = ConfigHolder.getInstance().getString("spectra.name"),
            output = ConfigHolder.getInstance().getString("output");
    int correctionFactor = ConfigHolder.getInstance().getInt("correctionFactor");
    boolean theoFromAllCharges = ConfigHolder.getInstance().getBoolean("hasAllPossCharge");
    BufferedWriter bw = new BufferedWriter(new FileWriter(output));
    bw.write("SpectrumTitle" + "\t" + "PrecursorMZ" + "\t" + "PrecursorCharge" + "\t" + "Observed Mass (M+H)"
            + "\t" + "AndromedaLikeScore" + "\t" + "SequestLikeScore" + "\t" + "PeptideByAndromedaLikeScore"
            + "\t" + "PeptideBySequestLikeScore" + "\t" + "LevenshteinDistance" + "\t" + "TotalScoredPeps"
            + "\t" + "isCorrectMatchByAndromedaLike" + "\t" + "isCorrectMatchBySequestLikeScore" + "\n");
    l.info("Getting database entries");
    // first load all sequences into the memory 
    HashSet<DBEntry> dbEntries = getDBEntries(databaseName);
    // for every spectrum-calculate both score...
    // now convert to binExperimental spectrum
    int num = 0;
    SpectrumFactory fct = SpectrumFactory.getInstance();
    num = 0;
    File f = new File(spectraName);
    if (spectraName.endsWith(".mgf")) {
        fct.addSpectra(f, new WaitingHandlerCLIImpl());
        l.log(Level.INFO, "Spectra scoring starts at {0}", now);
        for (String title : fct.getSpectrumTitles(f.getName())) {
            num++;
            MSnSpectrum ms = (MSnSpectrum) fct.getSpectrum(f.getName(), title);
            // here calculate all except this is an empty spectrum...
            if (ms.getPeakList().size() > 2) {
                // to check a spectrum with negative values..
                String text = result(ms, precursorTolerance, dbEntries, fragmentTolerance, correctionFactor,
                        theoFromAllCharges);
                if (!text.isEmpty()) {
                    bw.write(text);
                }
            }
            if (num % 500 == 0) {
                l.info("Running " + num + " spectra." + Calendar.getInstance().getTime());
            }
        }
    }
    l.info("Program finished at " + Calendar.getInstance().getTime());

    bw.close();
}

From source file:org.schemaspy.Main.java

public static void main(String[] argv) throws Exception {
    Logger logger = Logger.getLogger(Main.class.getName());

    final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
            "org.schemaspy.service");
    applicationContext.register(SchemaAnalyzer.class);

    if (argv.length == 1 && "-gui".equals(argv[0])) { // warning: serious temp hack
        new MainFrame().setVisible(true);
        return;//from  w w w .  j a  v  a2  s.  c om
    }

    SchemaAnalyzer analyzer = applicationContext.getBean(SchemaAnalyzer.class);

    int rc = 1;

    try {
        rc = analyzer.analyze(new Config(argv)) == null ? 1 : 0;
    } catch (ConnectionFailure couldntConnect) {
        logger.log(Level.WARNING, "Connection Failure", couldntConnect);
        rc = 3;
    } catch (EmptySchemaException noData) {
        logger.log(Level.WARNING, "Empty schema", noData);
        rc = 2;
    } catch (InvalidConfigurationException badConfig) {
        logger.info("");
        if (badConfig.getParamName() != null)
            logger.log(Level.WARNING, "Bad parameter specified for " + badConfig.getParamName());
        logger.log(Level.WARNING, "Bad config " + badConfig.getMessage());
        if (badConfig.getCause() != null && !badConfig.getMessage().endsWith(badConfig.getMessage()))
            logger.log(Level.WARNING, " caused by " + badConfig.getCause().getMessage());

        logger.log(Level.FINE, "Command line parameters: " + Arrays.asList(argv));
        logger.log(Level.FINE, "Invalid configuration detected", badConfig);
    } catch (ProcessExecutionException badLaunch) {
        logger.log(Level.WARNING, badLaunch.getMessage(), badLaunch);
    } catch (Exception exc) {
        logger.log(Level.SEVERE, exc.getMessage(), exc);
    }

    System.exit(rc);
}

From source file:net.sf.freecol.FreeCol.java

/**
 * The entrypoint.//from ww w . j  a va  2  s  .c  o m
 *
 * @param args The command-line arguments.
 * @throws IOException 
 * @throws FontFormatException 
 */
public static void main(String[] args) throws FontFormatException, IOException {
    freeColRevision = FREECOL_VERSION;
    JarURLConnection juc;
    try {
        juc = getJarURLConnection(FreeCol.class);
    } catch (IOException ioe) {
        juc = null;
        System.err.println("Unable to open class jar: " + ioe.getMessage());
    }
    if (juc != null) {
        try {
            String revision = readVersion(juc);
            if (revision != null) {
                freeColRevision += " (Revision: " + revision + ")";
            }
        } catch (Exception e) {
            System.err.println("Unable to load Manifest: " + e.getMessage());
        }
        try {
            splashStream = getDefaultSplashStream(juc);
        } catch (Exception e) {
            System.err.println("Unable to open default splash: " + e.getMessage());
        }
    }

    // Java bug #7075600 causes BR#2554.  The workaround is to set
    // the following property.  Remove if/when they fix Java.
    System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");

    // We can not even emit localized error messages until we find
    // the data directory, which might have been specified on the
    // command line.
    String dataDirectoryArg = findArg("--freecol-data", args);
    String err = FreeColDirectories.setDataDirectory(dataDirectoryArg);
    if (err != null)
        fatal(err); // This must not fail.

    // Now we have the data directory, establish the base locale.
    // Beware, the locale may change!
    String localeArg = findArg("--default-locale", args);
    if (localeArg == null) {
        locale = Locale.getDefault();
    } else {
        int index = localeArg.indexOf('.'); // Strip encoding if present
        if (index > 0)
            localeArg = localeArg.substring(0, index);
        locale = Messages.getLocale(localeArg);
    }
    Messages.loadMessageBundle(locale);

    // Now that we can emit error messages, parse the other
    // command line arguments.
    handleArgs(args);

    // Do the potentially fatal system checks as early as possible.
    if (javaCheck && JAVA_VERSION_MIN.compareTo(JAVA_VERSION) > 0) {
        fatal(StringTemplate.template("main.javaVersion").addName("%version%", JAVA_VERSION)
                .addName("%minVersion%", JAVA_VERSION_MIN));
    }
    if (memoryCheck && MEMORY_MAX < MEMORY_MIN * 1000000) {
        fatal(StringTemplate.template("main.memory").addAmount("%memory%", MEMORY_MAX).addAmount("%minMemory%",
                MEMORY_MIN));
    }

    // Having parsed the command line args, we know where the user
    // directories should be, so we can set up the rest of the
    // file/directory structure.
    String userMsg = FreeColDirectories.setUserDirectories();

    // Now we have the log file path, start logging.
    final Logger baseLogger = Logger.getLogger("");
    final Handler[] handlers = baseLogger.getHandlers();
    for (Handler handler : handlers) {
        baseLogger.removeHandler(handler);
    }
    String logFile = FreeColDirectories.getLogFilePath();
    try {
        baseLogger.addHandler(new DefaultHandler(consoleLogging, logFile));
        Logger freecolLogger = Logger.getLogger("net.sf.freecol");
        freecolLogger.setLevel(logLevel);
    } catch (FreeColException e) {
        System.err.println("Logging initialization failure: " + e.getMessage());
        e.printStackTrace();
    }
    Thread.setDefaultUncaughtExceptionHandler((Thread thread, Throwable e) -> {
        baseLogger.log(Level.WARNING, "Uncaught exception from thread: " + thread, e);
    });

    // Now we can find the client options, allow the options
    // setting to override the locale, if no command line option
    // had been specified.
    // We have users whose machines default to Finnish but play
    // FreeCol in English.
    // If the user has selected automatic language selection, do
    // nothing, since we have already set up the default locale.
    if (localeArg == null) {
        String clientLanguage = ClientOptions.getLanguageOption();
        Locale clientLocale;
        if (clientLanguage != null && !Messages.AUTOMATIC.equalsIgnoreCase(clientLanguage)
                && (clientLocale = Messages.getLocale(clientLanguage)) != locale) {
            locale = clientLocale;
            Messages.loadMessageBundle(locale);
            logger.info("Loaded messages for " + locale);
        }
    }

    // Now we have the user mods directory and the locale is now
    // stable, load the mods and their messages.
    Mods.loadMods();
    Messages.loadModMessageBundle(locale);

    // Report on where we are.
    if (userMsg != null)
        logger.info(Messages.message(userMsg));
    logger.info(getConfiguration().toString());

    // Ready to specialize into client or server.
    if (standAloneServer) {
        startServer();
    } else {
        startClient(userMsg);
    }
    startYourAddition();
}

From source file:org.activiti.cycle.impl.connector.signavio.SignavioLogHelper.java

public static void logJSONArray(Logger log, JSONArray jsonArray) {
    try {//from ww  w. jav a 2 s. com
        log.info(jsonArray.toString(2));
    } catch (JSONException je) {
        log.log(Level.SEVERE, "JSONException while trying to log JSONArray", je);
    }
}

From source file:com.stratuscom.harvester.Utils.java

public static void logClassLoaderHierarchy(Logger log, Level level, Class cls) {
    log.log(level, MessageNames.CLASSLOADER_IS, new Object[] { cls.getName(), cls.getClassLoader() });
    try {//w  w  w. j ava 2s  .  c o  m
        ClassLoader parent = cls.getClassLoader().getParent();
        while (parent != null) {
            log.log(level, MessageNames.PARENT_CLASS_LOADER_IS, new Object[] { parent });
            parent = parent.getParent();
        }
    } catch (Throwable t) {
        log.log(level, Strings.NEWLINE);
    }

}

From source file:com.stratuscom.harvester.Utils.java

public static void logClassLoaderHierarchy(Logger log, Level level, ClassLoader loader) {
    log.log(level, MessageNames.CLASSLOADER_IS, new Object[] { null, loader });
    ClassLoader parent = loader.getParent();
    while (parent != null) {
        log.log(level, MessageNames.PARENT_CLASS_LOADER_IS, new Object[] { parent });
        try {/* w  ww .j  a va2 s .c  o  m*/
            parent = parent.getParent();
        } catch (Throwable t) {
            parent = null;
        }
    }
}

From source file:io.trivium.anystore.StoreUtils.java

public static void createIfNotExists(String url) {
    Logger logger = Logger.getLogger(StoreUtils.class.getName());
    File m = new File(url);
    if (!m.exists()) {
        m.mkdirs();/*from w w  w. j  a v  a  2s  .co m*/
        logger.log(Level.FINE, "creating directory {}", url);
    }
}