List of usage examples for java.util.logging LogRecord setParameters
public void setParameters(Object parameters[])
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 {//from ww w.ja v a 2 s.c om 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: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 w w w . j ava 2 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: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./* ww w .java2 s .c o m*/ */ 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();// ww w .ja va 2s.co 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: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 ww w .j a v a2 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: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 a va 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:com.cloudbees.jenkins.support.SupportPlugin.java
@Override public void postInitialize() throws Exception { super.postInitialize(); for (Component component : getComponents()) { try {//from w ww . j a v a 2 s. c om 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:hudson.model.Computer.java
/** * This method tries to compute the name of the host that's reachable by all the other nodes. * * <p>//from w w w. java2s . c o m * Since it's possible that the agent is not reachable from the master (it may be behind a firewall, * connecting to master via JNLP), this method may return null. * * It's surprisingly tricky for a machine to know a name that other systems can get to, * especially between things like DNS search suffix, the hosts file, and YP. * * <p> * So the technique here is to compute possible interfaces and names on the agent, * then try to ping them from the master, and pick the one that worked. * * <p> * The computation may take some time, so it employs caching to make the successive lookups faster. * * @since 1.300 * @return * null if the host name cannot be computed (for example because this computer is offline, * because the agent is behind the firewall, etc.) */ public String getHostName() throws IOException, InterruptedException { if (hostNameCached) // in the worst case we end up having multiple threads computing the host name simultaneously, but that's not harmful, just wasteful. return cachedHostName; VirtualChannel channel = getChannel(); if (channel == null) return null; // can't compute right now for (String address : channel.call(new ListPossibleNames())) { try { InetAddress ia = InetAddress.getByName(address); if (!(ia instanceof Inet4Address)) { LOGGER.log(Level.FINE, "{0} is not an IPv4 address", address); continue; } if (!ComputerPinger.checkIsReachable(ia, 3)) { LOGGER.log(Level.FINE, "{0} didn't respond to ping", address); continue; } cachedHostName = ia.getCanonicalHostName(); hostNameCached = true; return cachedHostName; } catch (IOException e) { // if a given name fails to parse on this host, we get this error LogRecord lr = new LogRecord(Level.FINE, "Failed to parse {0}"); lr.setThrown(e); lr.setParameters(new Object[] { address }); LOGGER.log(lr); } } // allow the administrator to manually specify the host name as a fallback. HUDSON-5373 cachedHostName = channel.call(new GetFallbackName()); hostNameCached = true; return cachedHostName; }
From source file:jenkins.branch.MultiBranchProject.java
/** * {@inheritDoc}/*w w w . j a v a2 s . c o 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:alma.acs.logging.AcsLogger.java
/** * Logs the given <code>LogRecord</code>. * The record can be modified or dropped by the optional filters provided in {@link #addLogRecordFilter(alma.acs.logging.AcsLogger.LogRecordFilter)}. * <p>/*w ww. ja v a 2 s .c o m*/ * Adding of context information: * <ul> * <li> If the LogRecord has a parameter that is a map which contains additional information * about the line of code, thread, etc., the log record will be taken as provided, and no context * information will be added. This can be useful if * <ul> * <li> the log record was reconstructed from a remote error by the ACS error handling code * (see <code>AcsJException</code>), or * <li> if in very exceptional cases application code needs to manipulate such information by hand. * </ul> * <li> otherwise, context information is inferred, similar to {@link LogRecord#inferCaller()}, * but additionally including thread name and line of code. * </ul> * Note that by overloading this method, we intercept all logging activities of the base class. * * @see java.util.logging.Logger#log(java.util.logging.LogRecord) */ public void log(LogRecord record) { // Throw exception if level OFF was used to log this record, see http://jira.alma.cl/browse/COMP-1928 // Both Level.OFF and AcsLogLevel.OFF use the same value INTEGER.max, but we anyway check for both. if (record.getLevel().intValue() == Level.OFF.intValue() || record.getLevel().intValue() == AcsLogLevel.OFF.intValue()) { throw new IllegalArgumentException( "Level OFF must not be used for actual logging, but only for level filtering."); } StopWatch sw_all = null; if (PROFILE) { sw_all = new StopWatch(null); } // Level could be null and must then be inherited from the ancestor loggers, // e.g. during JDK shutdown when the log level is nulled by the JDK LogManager Logger loggerWithLevel = this; while (loggerWithLevel != null && loggerWithLevel.getLevel() == null && loggerWithLevel.getParent() != null) { loggerWithLevel = loggerWithLevel.getParent(); } int levelValue = -1; if (loggerWithLevel.getLevel() == null) { // HSO 2007-09-05: With ACS 6.0.4 the OMC uses this class (previously plain JDK logger) and has reported // that no level was found, which yielded a NPE. To be investigated further. // Probably #createUnconfiguredLogger was used without setting parent logger nor log level. // Just to be safe I add the necessary checks and warning message that improve over a NPE. if (!noLevelWarningPrinted) { System.out.println("Logger configuration error: no log level found for logger " + getLoggerName() + " or its ancestors. Will use Level.ALL instead."); noLevelWarningPrinted = true; } // @TODO: decide if resorting to ALL is desirable, or to use schema defaults, INFO, etc levelValue = Level.ALL.intValue(); } else { // level is fine, reset the flag to print the error message again when log level is missing. noLevelWarningPrinted = false; levelValue = loggerWithLevel.getLevel().intValue(); } // filter by log level to avoid unnecessary retrieval of context data. // The same check will be repeated by the base class implementation of this method that gets called afterwards. if (record.getLevel().intValue() < levelValue || levelValue == offValue) { return; } // modify the logger name if necessary if (loggerName != null) { record.setLoggerName(loggerName); } // check if this record already has the context data attached which ACS needs but the JDK logging API does not provide LogParameterUtil paramUtil = new LogParameterUtil(record); Map<String, Object> specialProperties = paramUtil.extractSpecialPropertiesMap(); if (specialProperties == null) { // we prepend the special properties map to the other parameters specialProperties = LogParameterUtil.createPropertiesMap(); List<Object> paramList = paramUtil.getNonSpecialPropertiesMapParameters(); paramList.add(0, specialProperties); record.setParameters(paramList.toArray()); String threadName = Thread.currentThread().getName(); specialProperties.put(LogParameterUtil.PARAM_THREAD_NAME, threadName); specialProperties.put(LogParameterUtil.PARAM_PROCESSNAME, this.processName); specialProperties.put(LogParameterUtil.PARAM_SOURCEOBJECT, this.sourceObject); // Get the stack trace StackTraceElement stack[] = (new Throwable()).getStackTrace(); // search for the first frame before the "Logger" class. int ix = 0; boolean foundNonLogFrame = false; while (ix < stack.length) { StackTraceElement frame = stack[ix]; String cname = frame.getClassName(); if (!foundNonLogFrame && !loggerClassNames.contains(cname)) { // We've found the relevant frame. record.setSourceClassName(cname); record.setSourceMethodName(frame.getMethodName()); int lineNumber = frame.getLineNumber(); specialProperties.put(LogParameterUtil.PARAM_LINE, Long.valueOf(lineNumber)); foundNonLogFrame = true; if (this.callStacksToBeIgnored.isEmpty()) { break; // performance optimization: avoid checking all "higher" stack frames } } if (foundNonLogFrame) { if (callStacksToBeIgnored.contains(concatenateIgnoreLogData(cname, frame.getMethodName()))) { //System.out.println("Won't log record with message " + record.getMessage()); return; } } ix++; } // We haven't found a suitable frame, so just punt. This is // OK as we are only committed to making a "best effort" here. } StopWatch sw_afterAcsLogger = null; if (PROFILE) { sw_afterAcsLogger = sw_all.createStopWatchForSubtask("afterAcsLogger"); LogParameterUtil logParamUtil = new LogParameterUtil(record); logParamUtil.setStopWatch(sw_afterAcsLogger); } // Let the delegate or Logger base class handle the rest. if (delegate != null) { delegate.log(record); } else { super.log(record); } if (PROFILE) { sw_afterAcsLogger.stop(); sw_all.stop(); long elapsedNanos = sw_all.getLapTimeNanos(); if (profileSlowestCallStopWatch == null || profileSlowestCallStopWatch.getLapTimeNanos() < elapsedNanos) { profileSlowestCallStopWatch = sw_all; } profileLogTimeStats.addValue(elapsedNanos); if (profileLogTimeStats.getN() >= profileStatSize) { String msg = "Local logging times in ms for the last " + profileStatSize + " logs: "; msg += "mean=" + profileMillisecFormatter.format(profileLogTimeStats.getMean() * 1E-6); msg += ", median=" + profileMillisecFormatter.format(profileLogTimeStats.getPercentile(50) * 1E-6); msg += ", stdev=" + profileMillisecFormatter.format(profileLogTimeStats.getStandardDeviation() * 1E-6); msg += "; details of slowest log (from "; msg += IsoDateFormat.formatDate(profileSlowestCallStopWatch.getStartTime()) + "): "; msg += profileSlowestCallStopWatch.getSubtaskDetails(); System.out.println(msg); profileSlowestCallStopWatch = null; profileLogTimeStats.clear(); } } }