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:jenkins.branch.MultiBranchProject.java

/**
 * {@inheritDoc}/*from w  w w.  j  a  va2  s .co  m*/
 */
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
    super.onLoad(parent, name);
    init2();
    try {
        srcDigest = Util.getDigestOf(Items.XSTREAM2.toXML(sources));
    } catch (XStreamException e) {
        srcDigest = null;
    }
    BranchProjectFactory<P, R> factory = getProjectFactory();
    try {
        facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(factory));
    } catch (XStreamException e) {
        facDigest = null;
    }
    if (state == null) {
        state = new State(this);
    }
    try {
        state.load();
    } catch (XStreamException | IOException e) {
        LOGGER.log(Level.WARNING, "Could not read persisted state, will be recovered on next index.", e);
        state.reset();
    }
    // optimize lookup of sources by building a temporary map that is equivalent to getSCMSource(id) in results
    Map<String, SCMSource> sourceMap = new HashMap<>();
    for (BranchSource source : sources) {
        SCMSource s = source.getSource();
        String id = s.getId();
        if (!sourceMap.containsKey(id)) { // only the first match should win
            sourceMap.put(id, s);
        }
    }
    for (P item : getItems()) {
        if (factory.isProject(item)) {
            Branch oldBranch = factory.getBranch(item);
            SCMSource source = sourceMap.get(oldBranch.getSourceId());
            if (source == null || source instanceof NullSCMSource) {
                continue;
            }
            SCMHead oldHead = oldBranch.getHead();
            SCMHead newHead = SCMHeadMigration.readResolveSCMHead(source, oldHead);
            if (newHead != oldHead) {
                LOGGER.log(Level.INFO,
                        "Job {0}: a plugin upgrade is requesting migration of branch from {1} to {2}",
                        new Object[] { item.getFullName(), oldHead.getClass(), newHead.getClass() });
                try {
                    Branch newBranch = new Branch(oldBranch.getSourceId(), newHead, oldBranch.getScm(),
                            oldBranch.getProperties());
                    newBranch.setActions(oldBranch.getActions());
                    factory.setBranch(item, newBranch);
                    SCMRevision revision = factory.getRevision(item);
                    factory.setRevisionHash(item, SCMHeadMigration.readResolveSCMRevision(source, revision));
                } catch (IOException | RuntimeException e) {
                    LogRecord lr = new LogRecord(Level.WARNING,
                            "Job {0}: Could not complete migration of branch from type {1} to {2}. "
                                    + "The side-effect of this is that the next index may trigger a rebuild "
                                    + "of the job (after which the issue will be resolved)");
                    lr.setThrown(e);
                    lr.setParameters(
                            new Object[] { item.getFullName(), oldHead.getClass(), newHead.getClass() });
                    LOGGER.log(lr);
                }
            }
        }
    }
}

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

/** Figure out where we should upload the logs.
 *
 * We don't want to post/send the entire log only to be redirected at the end.
 * We'll do a HEAD request instead (assuming that both HEAD and POST are
 * redirected the same way) to see if there is any redirection, and if there
 * is, this gives us a chance to POST to the new URI.
 *
 * @return If the return is null, it means we encountered a (temporary or
 * permanent) error.// w ww .ja va  2s .com
 */
private String getUploadUrl() {
    final String url = pref.get(Options.OptStatsUploadUrl, STATS_UPLOAD);
    String newUrl = null;

    HttpRedirectStrategy httpRedirect = new HttpRedirectStrategy() {
        @Override
        public void handlePermanentRedirect(HttpRequest request, HttpResponse response,
                HttpUriRequest redirect) {
            if (!Utils.isNullOrEmpty(newUrl) && !newUrl.equals(url)) {
                pref.put(Options.OptStatsUploadUrl, newUrl);
            }
        }
    };

    CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(httpRedirect).build();
    HttpHead head = new HttpHead(url);
    addHttpHeaders(head);

    int status = 0;
    try (CloseableHttpResponse response = client.execute(head)) {
        status = response.getStatusLine().getStatusCode();

        if (status == HttpStatus.SC_OK) {
            if (httpRedirect.wasRedirected()) {
                newUrl = httpRedirect.getNewUrl();
            } else {
                newUrl = url;
            }
        } else {
            if (httpRedirect.wasRedirected()) {
                /* This means either we got an error either at the original URI
                or somewhere along the redirection chain. Either way, we restore
                the original URI in case one of the redirects caused us to update
                the options. */
                pref.put(Options.OptStatsUploadUrl, url);
            }
            newUrl = null;
        }

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
    } catch (IOException ex) {
        // Ignore it. We don't have a network connection
        // TODO: Distinguish b/w no network and ebixio.com being down?
    }

    if (newUrl == null) {
        LogRecord rec = new LogRecord(Level.INFO, "HTTP Err");
        rec.setParameters(
                new Object[] { url, "Status: " + status, "Redirect: " + httpRedirect.wasRedirected() });
        getLogger().log(rec);
    }

    return newUrl;
}

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

/** Should only be called from uploadLogs(). Compresses all files that belong
 to the given log set, and uploads all compressed files to the server. */
private boolean uploadLogs(final String logSet) {
    if (logSet == null)
        return false;

    File logsDir = getLogsDir();// w  w w . java 2 s .c o  m
    if (logsDir == null)
        return false;
    gzipLogs(logsDir, logSet);

    // Uploading only gz'd files
    FilenameFilter gzFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".gz");
        }
    };
    File[] toUpload = logsDir.listFiles(gzFilter);

    String url = getUploadUrl();
    if (url == null) {
        /* This means the server is unable to accept the logs. */
        keepRecents(toUpload, 100);
        return false;
    }

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    addHttpHeaders(post);

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("InstallId", new StringBody(String.valueOf(MainApp.getInstallId()), ContentType.TEXT_PLAIN));

    ContentType ct = ContentType.create("x-application/gzip");
    for (File f : toUpload) {
        entity.addPart("VirtMusStats", new FileBody(f, ct, f.getName()));
    }
    post.setEntity(entity.build());

    boolean success = false;
    try (CloseableHttpResponse response = client.execute(post)) {
        int status = response.getStatusLine().getStatusCode();
        Log.log(Level.INFO, "Log upload result: {0}", status);
        if (status == HttpStatus.SC_OK) { // 200
            for (File f : toUpload) {
                try {
                    f.delete();
                } catch (SecurityException ex) {
                }
            }
            success = true;
        } else {
            LogRecord rec = new LogRecord(Level.INFO, "Server Err");
            rec.setParameters(new Object[] { url, "Status: " + status });
            getLogger().log(rec);
        }

        HttpEntity rspEntity = response.getEntity();
        EntityUtils.consume(rspEntity);
        client.close();
    } catch (IOException ex) {
        Log.log(ex);
    }

    keepRecents(toUpload, 100); // In case of exceptions or errors
    return success;
}

From source file:hudson.FunctionsTest.java

@Issue("JENKINS-20800")
@Test//  ww  w  .j a  v a  2s .co m
public void printLogRecordHtml() throws Exception {
    LogRecord lr = new LogRecord(Level.INFO, "Bad input <xml/>");
    lr.setLoggerName("test");
    assertEquals("Bad input &lt;xml/&gt;\n", Functions.printLogRecordHtml(lr, null)[3]);
}

From source file:org.apache.cxf.common.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);/*w  ww  .  j av  a2s .com*/
    }

    //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:samplecode.search.EveryEntry.java

/**
 * Starts all threads, one thread per task.
 *
 * @param executorService// w  w w . java  2 s .  c om
 *   the service providing a thread pool in which to execute
 *   tasks.
 * @param numThreads
 *   the number of threads (and tasks since there is one task
 *   per thread).
 *
 * @return a single result code.
 */
private ResultCode startSearches(final ExecutorService executorService, final int numThreads) {
    Validator.ensureNotNull(executorService);
    ResultCode resultCode = ResultCode.SUCCESS;
    for (int t = 0; t < numThreads; ++t) {
        final String searchListenerClassname = commandLineOptions.getSearchResultListenerClassname();
        EveryEntryImpl impl;
        try {
            /*
             * Get a connection to the server and create an error listener
             * for later assignment to a task. Create the task and submit to
             * the executor service.
             */
            final LDAPConnection ldapConnection = getConnection();
            final List<ErrorListener<ResultCode>> errorListeners = SampleCodeCollectionUtils.newArrayList();
            final ErrorListener<ResultCode> l = new ResultCodeErrorListener();
            errorListeners.add(l);
            impl = new EveryEntryImpl(searchListenerClassname, commandLineOptions, ldapConnection, getErr(),
                    errorListeners);
            final Log logger = LogFactory.getLog(getClass());
            final LdapExceptionListener ldapExceptionListener = new DefaultLdapExceptionListener(logger);
            impl.addLdapExceptionListener(ldapExceptionListener);
            executorService.submit(impl);
        } catch (final LDAPException ldapException) {
            resultCode = ldapException.getResultCode();
        } catch (final InstantiationException instantiationException) {
            err(formatter.format(new LogRecord(Level.SEVERE,
                    "Cannot instantiate " + instantiationException.getLocalizedMessage())));
            resultCode = ResultCode.PARAM_ERROR;
        } catch (final IllegalAccessException e) {
            resultCode = ResultCode.OPERATIONS_ERROR;
        } catch (final ClassNotFoundException classNotFoundException) {
            err(formatter
                    .format(new LogRecord(Level.SEVERE,
                            String.format(
                                    "The class '%s' " + "specified as the search "
                                            + "result listener could not be found.",
                                    searchListenerClassname))));
            resultCode = ResultCode.PARAM_ERROR;
        }
    }
    return resultCode;
}

From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java

private static void log(Logger logger, String prefix, String message) {
    if (logger != null && !filteredLogs.contains(message)) {
        LogRecord record = null;/* w  w w  .  ja v  a  2 s.c o m*/
        if (message.startsWith(">")) {
            String[] parts = message.substring(1).split("/", 3);
            record = new LogRecord(Level.parse(parts[0]),
                    new StringBuilder().append(prefix).append(" ").append(parts[2]).toString());
            record.setSourceMethodName(parts[1]);
            record.setSourceClassName(JBrowserDriver.class.getName());
        } else {
            record = new LogRecord(Level.WARNING,
                    new StringBuilder().append(prefix).append(" ").append(message).toString());
            record.setSourceMethodName(null);
            record.setSourceClassName(JBrowserDriver.class.getName());
        }
        logger.log(record);
    }
}

From source file:com.cloudbees.jenkins.support.SupportPlugin.java

@Override
public void postInitialize() throws Exception {
    super.postInitialize();
    for (Component component : getComponents()) {
        try {//from w ww  . ja v  a  2  s  .c  o  m
            component.start(getContext());
        } catch (Throwable t) {
            LogRecord logRecord = new LogRecord(Level.WARNING, "Exception propagated from component: {0}");
            logRecord.setThrown(t);
            logRecord.setParameters(new Object[] { component.getDisplayName() });
            logger.log(logRecord);
        }
    }
}

From source file:com.cloudbees.jenkins.support.SupportPlugin.java

public List<LogRecord> getAllLogRecords(final Node node) throws IOException, InterruptedException {
    if (node != null) {
        VirtualChannel channel = node.getChannel();
        if (channel != null) {
            final Future<List<LogRecord>> future = channel.callAsync(new LogFetcher());
            try {
                return future.get(REMOTE_OPERATION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
            } catch (ExecutionException e) {
                final LogRecord lr = new LogRecord(Level.WARNING, "Could not retrieve remote log records");
                lr.setThrown(e);/*from  w  w  w .  ja v a 2  s. c om*/
                return Collections.singletonList(lr);
            } catch (TimeoutException e) {
                Computer.threadPoolForRemoting.submit(() -> {
                    List<LogRecord> records;
                    try {
                        records = future.get(REMOTE_OPERATION_CACHE_TIMEOUT_SEC, TimeUnit.SECONDS);
                    } catch (InterruptedException e1) {
                        final LogRecord lr = new LogRecord(Level.WARNING,
                                "Could not retrieve remote log records");
                        lr.setThrown(e1);
                        records = Collections.singletonList(lr);
                    } catch (ExecutionException e1) {
                        final LogRecord lr = new LogRecord(Level.WARNING,
                                "Could not retrieve remote log records");
                        lr.setThrown(e1);
                        records = Collections.singletonList(lr);
                    } catch (TimeoutException e1) {
                        final LogRecord lr = new LogRecord(Level.WARNING,
                                "Could not retrieve remote log records");
                        lr.setThrown(e1);
                        records = Collections.singletonList(lr);
                        future.cancel(true);
                    }
                    synchronized (SupportPlugin.this) {
                        if (logRecords == null) {
                            logRecords = new WeakHashMap<>();
                        }
                        logRecords.put(node, records);
                    }
                });
                synchronized (this) {
                    if (logRecords != null) {
                        List<LogRecord> result = logRecords.get(node);
                        if (result != null) {
                            result = new ArrayList<>(result);
                            final LogRecord lr = new LogRecord(Level.WARNING,
                                    "Using cached remote log records");
                            lr.setThrown(e);
                            result.add(lr);
                            return result;
                        }
                    } else {
                        final LogRecord lr = new LogRecord(Level.WARNING,
                                "No previous cached remote log records");
                        lr.setThrown(e);
                        return Collections.singletonList(lr);
                    }
                }
            }
        }
    }
    return Collections.emptyList();
}

From source file:samplecode.search.EveryEntry.java

/**
 * {@inheritDoc}//from  ww  w  .  j a v  a 2s .  c  om
 * <p/>
 * Sends a message on the {@code errStream} that will include the
 * {@code resultCode}.
 */
@Override
public void displayError(final PrintStream errStream, final ResultCode resultCode) {
    Validator.ensureNotNull(resultCode);
    final String msg = String.format("An error condition occurred: %s", resultCode);
    final LogRecord record = new LogRecord(Level.SEVERE, msg);
    errStream.println(new MinimalLogFormatter().format(record));
}