下面列出了java.util.logging.LogRecord#setLoggerName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private LogRecord eventToRecord(LoggingEvent event, Level julLevel) {
String format = event.getMessage();
Object[] arguments = event.getArgumentArray();
FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments);
if (ft.getThrowable() != null && event.getThrowable() != null) {
throw new IllegalArgumentException("both last element in argument array and last argument are of type Throwable");
}
Throwable t = event.getThrowable();
if (ft.getThrowable() != null) {
t = ft.getThrowable();
throw new IllegalStateException("fix above code");
}
LogRecord record = new LogRecord(julLevel, ft.getMessage());
record.setLoggerName(event.getLoggerName());
record.setMillis(event.getTimeStamp());
record.setSourceClassName(EventConstants.NA_SUBST);
record.setSourceMethodName(EventConstants.NA_SUBST);
record.setThrown(t);
return record;
}
public void setCurrentProfile (String profileName) {
String prev = getCurrentProfile();
if (!prev.equals(profileName)) {
LogRecord rec = new LogRecord(Level.CONFIG, "KEYMAP_SET_PROFILE"); // NOI18N
rec.setParameters(new Object[]{ profileName, prev });
rec.setResourceBundle(NbBundle.getBundle(KeymapModel.class));
rec.setResourceBundleName(KeymapModel.class.getPackage().getName() + ".Bundle");
rec.setLoggerName(UI_LOG.getName());
UI_LOG.log(rec);
}
final String profile = displayNameToName(profileName);
waitFinished(new Runnable() {
public void run() {
for (KeymapManager m : getKeymapManagerInstances()) {
m.setCurrentProfile(profile);
}
profileData = null;
}
});
}
public static void generate() {
try {
LogRecord record = new LogRecord(Level.INFO, "Java Version: {0}");
record.setLoggerName("test");
record.setParameters(new Object[] {System.getProperty("java.version")});
System.out.println(generate(record));
} catch (IOException | ClassNotFoundException x) {
throw new RuntimeException(x);
}
}
/**
* {@inheritDoc}
* <p>
* Overridden to create a {@link LogRecord} based on the log information.
* </p>
*
* @see Log#log(Level, Throwable, String, Object[])
*/
@Override
protected final void doLog(final Level level, final Throwable thrown,
final String template, final Object... args) {
if (myDelegate.isLoggable(level)) {
final Thread currentThread = Thread.currentThread();
final LogRecord record = new LogRecord(level,
format(template, args));
record.setLoggerName(myDelegate.getName());
record.setThrown(thrown);
record.setThreadID((int) Thread.currentThread().getId());
// Note the name of the class is the AbstractLog which is where all
// of the public log methods are implemented.
boolean lookingForThisClass = true;
for (final StackTraceElement element : currentThread
.getStackTrace()) {
final String className = element.getClassName();
// Find this method (and maybe others from this class).
if (lookingForThisClass) {
lookingForThisClass = !CLASS_NAME.equals(className);
}
else {
// And back until we are past this class.
if (!CLASS_NAME.equals(className)) {
record.setSourceClassName(className);
record.setSourceMethodName(element.getMethodName());
break;
}
}
}
// Finally - log it.
myDelegate.log(record);
}
}
/**
* Logs the given exception at the given level. This method pretends that the logging come from
* {@link CRS#getAuthorityFactory(String)}, which is the public facade for {@link #EPSG()}.
*/
private static void log(final Exception e, final boolean isWarning) {
String message = e.getMessage(); // Prefer the locale of system administrator.
if (message == null) {
message = e.toString();
}
final LogRecord record = new LogRecord(isWarning ? Level.WARNING : Level.CONFIG, message);
if (isWarning && !(e instanceof UnavailableFactoryException)) {
record.setThrown(e);
}
record.setLoggerName(Loggers.CRS_FACTORY);
Logging.log(CRS.class, "getAuthorityFactory", record);
}
public static void generate() {
try {
LogRecord record = new LogRecord(Level.INFO, "Java Version: {0}");
record.setLoggerName("test");
record.setParameters(new Object[] {System.getProperty("java.version")});
System.out.println(generate(record));
} catch (IOException | ClassNotFoundException x) {
throw new RuntimeException(x);
}
}
public void testGenerateTooLittleLogs() throws Exception {
LogRecord r = new LogRecord(Level.INFO, "MSG_SOMETHING");
r.setLoggerName(Installer.UI_LOGGER_NAME + ".anything");
String utf8 =
"<html><head>" +
"</head>" +
"<body>" +
"<form action='http://anna.nbextras.org/analytics/upload.jsp' method='post'>" +
" <input name='submit' value='&Fill Survey' type='hidden'> </input>" +
"</form>" +
"</body></html>";
ByteArrayInputStream is = new ByteArrayInputStream(utf8.getBytes("utf-8"));
MemoryURL.registerURL("memory://start.html", is);
for (int i = 0; i < 500; i++) {
Logger.getLogger(Installer.UI_LOGGER_NAME + ".anything").log(r);
}
assertEquals("not full buffer", 500, InstallerTest.getLogsSize());
assertNull("No dialogs so far", DD.d);
installer.doClose();
waitForGestures();
assertNull("No dialogs at close", DD.d);
installer.restored();
waitForGestures();
assertNull("No dialog shown at begining", DD.d);
}
private static void log(String type, List<String> params) {
LogRecord record = new LogRecord(Level.INFO, type);
record.setResourceBundle(NbBundle.getBundle(GestureSubmitter.class));
record.setResourceBundleName(GestureSubmitter.class.getPackage().getName() + ".Bundle"); // NOI18N
record.setLoggerName(USG_LOGGER.getName());
record.setParameters(params.toArray(new Object[params.size()]));
USG_LOGGER.log(record);
}
/**
* Logs a vcs client action usage.
*
* @param vcs - the particular vcs "SVN", "CVS", "CC", "HG", ...
*/
public static void logVCSActionEvent(String vcs) {
String key = "USG_VCS_ACTION" + vcs;
if (checkMetricsKey(key)) return;
LogRecord rec = new LogRecord(Level.INFO, "USG_VCS_ACTION");
rec.setParameters(new Object[] { vcs });
rec.setLoggerName(METRICS_LOG.getName());
METRICS_LOG.log(rec);
}
@Before
public void setUp() {
System.setProperty("config.id", "my-test-config-id");
System.setProperty("vespa.log.target", "file:test3");
zookeeperLogRecord = new LogRecord(Level.WARNING, "zookeeper log record");
zookeeperLogRecord.setLoggerName("org.apache.zookeeper.server.NIOServerCnxn");
zookeeperLogRecord.setInstant(Instant.ofEpochMilli(1107011348029L));
curatorLogRecord = new LogRecord(Level.WARNING, "curator log record");
curatorLogRecord.setLoggerName("org.apache.curator.utils.DefaultTracerDriver");
curatorLogRecord.setInstant(Instant.ofEpochMilli(1107011348029L));
hostname = Util.getHostName();
pid = Util.getPID();
zookeeperLogRecordString = "1107011348.029000\t"
+ hostname
+ "\t"
+ pid
+ "/" + zookeeperLogRecord.getThreadID() + "\t-\t.org.apache.zookeeper.server.NIOServerCnxn"
+ "\twarning\tzookeeper log record";
zookeeperLogRecordError = new LogRecord(Level.SEVERE, "zookeeper error");
zookeeperLogRecordError.setLoggerName("org.apache.zookeeper.server.NIOServerCnxn");
zookeeperLogRecordError.setInstant(Instant.ofEpochMilli(1107011348029L));
curatorLogRecordError = new LogRecord(Level.SEVERE, "curator log record");
curatorLogRecordError.setLoggerName("org.apache.curator.utils.DefaultTracerDriver");
curatorLogRecordError.setInstant(Instant.ofEpochMilli(1107011348029L));
notzookeeperLogRecord = new LogRecord(Level.WARNING, "not zookeeper log record");
notzookeeperLogRecord.setLoggerName("org.apache.foo.Bar");
notzookeeperLogRecord.setInstant(Instant.ofEpochMilli(1107011348029L));
}
/**
* Reports an exception. This is used if an exception occurred in a method that can not return
* a {@link String} instance. This method logs the stack trace at {@link Level#WARNING}.
*
* @param method the method from which an exception occurred.
* @param exception the exception.
*/
final void reportException(final String method, final Exception exception) {
final Logger logger = getLogger();
final LogRecord record = new LogRecord(Level.WARNING, getLocalizedMessage(exception));
record.setLoggerName(logger.getName());
record.setSourceClassName(getClass().getName());
record.setSourceMethodName(method);
record.setThrown(exception);
logger.log(record);
}
public static void generate() {
try {
LogRecord record = new LogRecord(Level.INFO, "Java Version: {0}");
record.setLoggerName("test");
record.setParameters(new Object[] {System.getProperty("java.version")});
System.out.println(generate(record));
} catch (IOException | ClassNotFoundException x) {
throw new RuntimeException(x);
}
}
static LogRecord getUserInstalledModules(Logger logger) {
LogRecord rec = new LogRecord(Level.INFO, "USG_USER_INSTALLED_MODULES");
Set<String> clusterNames = new HashSet<String>(getClusterNames());
clusterNames.add("platform"); // NOI18N
List<ModuleInfo> userInstalledModules = new ArrayList<ModuleInfo>();
for (ModuleInfo mi : Lookup.getDefault().lookupAll(ModuleInfo.class)) {
Object showAttr = mi.getAttribute("AutoUpdate-Show-In-Client"); // NOI18N
if (!(showAttr instanceof String) ||
!Boolean.parseBoolean((String) showAttr)) {
continue;
}
File moduleJarFile = getModuleJarFile(mi);
if (moduleJarFile == null) {
continue;
}
File moduleParent = moduleJarFile.getParentFile();
if (moduleParent.getName().equals("modules")) { // NOI18N
String cn = moduleParent.getParentFile().getName();
if (!clusterNames.contains(cn)) {
userInstalledModules.add(mi);
}
}
}
rec.setParameters(getModuleNames(userInstalledModules));
rec.setLoggerName(logger.getName());
return rec;
}
/**
* Invoked when an exception occurred during the creation of a candidate from a code.
*/
private static void exceptionOccurred(final FactoryException exception) {
/*
* use 'getMessage()' instead of 'getLocalizedMessage()' for
* giving preference to the locale of system administrator.
*/
final LogRecord record = new LogRecord(Level.FINER, exception.getMessage());
record.setLoggerName(Loggers.CRS_FACTORY);
Logging.log(IdentifiedObjectFinder.class, "find", record);
}
protected void doLog( Level level, String key, Object[] params, Class wrapperClass,
Throwable thr )
{
LogRecord lrec = new LogRecord( level, key ) ;
if (params != null)
lrec.setParameters( params ) ;
inferCaller( wrapperClass, lrec ) ;
lrec.setThrown( thr ) ;
lrec.setLoggerName( loggerName );
lrec.setResourceBundle( logger.getResourceBundle() ) ;
logger.log( lrec ) ;
}
protected void doLog(final LogRecord lr) {
lr.setLoggerName(getName());
final String rbname = getResourceBundleName();
if (rbname != null) {
lr.setResourceBundleName(rbname);
lr.setResourceBundle(getResourceBundle());
}
internalLog(lr);
}
/**
* Logs bugtracking events
*
* @param key - the events key
* @param parameters - the parameters for the given event
*/
private static void logBugtrackingEvents(String key, Object[] parameters) {
LogRecord rec = new LogRecord(Level.INFO, key);
rec.setParameters(parameters);
rec.setLoggerName(METRICS_LOG.getName());
METRICS_LOG.log(rec);
}
/**
* 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.
* <p>
* See bug report #13 for more details.
*/
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(name());
record.setThrown(t);
fillCallerData(callerFQCN, record);
logger.log(record);
}
/**
* Logs a usage event.
*
* @param srcClass source class
* @param message message key
* @param params message parameters, may be <code>null</code>
*/
public static void logUsage(Class srcClass, String message, Object[] params) {
Parameters.notNull("message", message);
LogRecord logRecord = new LogRecord(Level.INFO, message);
logRecord.setLoggerName(USG_LOGGER.getName());
logRecord.setResourceBundle(NbBundle.getBundle(srcClass));
logRecord.setResourceBundleName(srcClass.getPackage().getName() + ".Bundle"); // NOI18N
if (params != null) {
logRecord.setParameters(params);
}
USG_LOGGER.log(logRecord);
}
/**
* Logs the given record. This method pretend that the record has been logged by
* {@code EPSGFactory.install(…)} because it is the public API using this class.
*/
static void log(final LogRecord record) {
record.setLoggerName(Loggers.CRS_FACTORY);
Logging.log(EPSGFactory.class, "install", record);
}