java.lang.Object
net.i2p.util.LogManager
- All Implemented Interfaces:
Flushable
Manages the logging system, loading (and reloading) the configuration file, coordinating the log limits, and storing the set of log records pending. This also fires off a LogWriter thread that pulls pending records off and writes them where appropriate.
As of 0.9.41, this class may be overridden via I2PAppContext.setLogManager(LogManager).
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate classThread flushing the logs at shutdown.Field Summary
Modifier and TypeFieldDescriptionprivate booleanTrue once the missing config file was logged.private StringLog filename pattern.private longWhen was the config file last read (or -1 if never).private final LogConsoleBufferThe actual "recent logs" list.private intHow many records we want to buffer in the "recent logs" list.private final I2PAppContextThe app context.private SimpleDateFormatDate format instance.private StringDate format string (for the SimpleDateFormat instance).private intDefault log level for logs that aren't explicitly controlled through a LogLimit in _limits.private booleanWhether or not we even want to display anything on stdout.private booleanTrue to drop repeated records.private booleanTrue to drop records when the buffer is full.private final AtomicLongRecords dropped since startup.private intMax bytes in the logfile before rotation.private intFlush interval of the writers, in seconds.private char[]Log record format string.private booleanTrue to compress the rotated logs.List of explicit overrides of log levels (LogLimit objects).private FileThe config file.private final LogLogger for the log manager itself.private intSize of the in memory log buffer.private final ConcurrentHashMap<Object, Log> String (scope) or Log.LogScope to Log object.private longSmallest rotated log that gets compressed.private intMinimum log level to be displayed on stdout.private final LinkedBlockingQueue<LogRecord> Ordered list of LogRecord elements that have not been written out yet.private intMax rotated logs.private booleanTrue once the manager has shut down.private LogWriterWho clears and writes our records.static final charFormat placeholder that expands to the logging class name.static final StringDefault logger config file name.static final StringProperty name for the logger config file location.static final charThese define the characters in the format line of the config file.static final intDefault number of entries in the console buffer.static final StringDate pattern used when none is configured.static final StringDefault log level string.static final booleanDefault setting for on-screen log display.static final StringDefault log file name pattern.static final StringDefault log file size limit as a string.static final StringDefault log record format string.private static final booleanDefault for compressing the rotated logs.private static final intDefault smallest log size to compress.static final StringDefault on-screen log level string.static final StringDefault log rotation limit.static final StringProperty name to override the log filename.private static final intMax LogRecords to buffer in memory before we start blocking.static final charFormat placeholder that expands to the log record's message.private static final intSmallest log file size allowed.static final charFormat placeholder that expands to the log record's priority.static final StringProperty name for the console buffer size.static final StringProperty name for the date format pattern.static final StringProperty name for the default log level.static final StringProperty name to enable or disable on-screen display.static final StringProperty name for the minimum log level displayed on screen.private static final StringConfig key to drop messages on buffer overflow.private static final StringConfig key for dropping duplicate messages.static final StringProperty name for the log file name pattern.static final StringProperty name for the log file size limit.private static final StringConfig key for the log flush interval.static final StringProperty name for the log record format string.static final StringProperty name for group-readable (660) log files.private static final StringConfig key for log gzipping.private static final StringConfig key for the log buffer size.private static final StringConfig key for the minimum log size to gzip.static final StringPrefix for per-logger level override properties.static final StringProperty name for the log rotation limit.static final charFormat placeholder that expands to the logging thread name.Constructor Summary
ConstructorsConstructorDescriptionLogManager(I2PAppContext context) Create the log manager for the given context.Method Summary
Modifier and TypeMethodDescription(package private) voidIf the log already exists, its priority is set here but cannot be changed later, as it becomes an "orphan" not tracked by the manager.(package private) voidUsed by Log to add records to the queue.private PropertiesWrites the default logging configuration.File may not exist or have old logs in it if not opened yet.booleanWhether log messages should be printed to stdout.voidflush()Flush any pending records to disk.Base log filename pattern.Return the circular buffer holding recent log records for console display.intMaximum number of entries held in the console buffer.(package private) I2PAppContextConvenience method for LogRecordFormatter.Any usage of returned formatter must be synchronized!Date format pattern string.Default limit for logs without explicit overrides, as a text string.intMinimum log level for messages printed to stdout.intMaximum log file size in bytes before rotation.static intgetFileSize(String size) Determine how many bytes are in the given formatted string (5m, 60g, 100k, etc) Size may be k, m, or g.char[]Log format characters.Return a mapping of the explicit overrides - path prefix to (text formatted) limit.Do not log here, deadlock of LogWriter via rereadConfig().final LogLog for the given class.final LogLog for the given class and name, creating it if necessary.final LogLog with the given name.getLogs()Return all currently cached Log instances.(package private) longMinimum size for gzip compression.getQueue()Zero-copy.intNumber of rotated log files to keep.private voidLoad and parse the logger configuration file if it has changed.private voidparseConfig(Properties config) Parse all configuration properties and set internal state accordingly.private voidparseLimits(Properties config) Do not log here, deadlock of LogWriter via rereadConfig().private voidparseLimits(Properties config, String recordPrefix) Do not log here, deadlock of LogWriter via rereadConfig().(package private) voidCalled periodically by the LogWriter thread to reload the config file.booleanSave the current logging configuration to disk.voidsetBaseLogfilename(String filenamePattern) Configure the base log filename pattern.final voidConfigure the logger from the given config file, reloading the configuration.booleansetDateFormat(String format) Update the date format Do not log here, deadlock of LogWriter via rereadConfig().voidsetDefaultLimit(String lim) Configure the default log limit from a text string.voidsetFileSize(int numBytes) Update the log file size limit.voidsetFormat(char[] fmt) Configure the log format characters.voidsetGzip(boolean yes) Enable or disable gzip compression for rotated log files.voidsetLimits(Properties limits) Update the existing limit overrides.(package private) booleanWhether duplicate log records should be dropped.booleanCheck if gzip compression should be used for rotated log files.voidshutdown()Shut down the log manager, flushing and stopping the writer.private voidStart the log writer thread, if it isn't running already.private voidupdateLimit(Log log) Do not log here, deadlock of LogWriter via rereadConfig().private voidDo not log here, deadlock of LogWriter via rereadConfig().
Field Details
CONFIG_LOCATION_PROP
Property name for the logger config file location.- See Also:
FILENAME_OVERRIDE_PROP
Property name to override the log filename.- See Also:
CONFIG_LOCATION_DEFAULT
Default logger config file name.- See Also:
DATE
public static final char DATEThese define the characters in the format line of the config file.- See Also:
CLASS
public static final char CLASSFormat placeholder that expands to the logging class name.- See Also:
THREAD
public static final char THREADFormat placeholder that expands to the logging thread name.- See Also:
PRIORITY
public static final char PRIORITYFormat placeholder that expands to the log record's priority.- See Also:
MESSAGE
public static final char MESSAGEFormat placeholder that expands to the log record's message.- See Also:
PROP_FORMAT
Property name for the log record format string.- See Also:
PROP_DATEFORMAT
Property name for the date format pattern.- See Also:
PROP_FILENAME
Property name for the log file name pattern.- See Also:
PROP_FILESIZE
Property name for the log file size limit.- See Also:
PROP_ROTATIONLIMIT
Property name for the log rotation limit.- See Also:
PROP_DISPLAYONSCREEN
Property name to enable or disable on-screen display.- See Also:
PROP_CONSOLEBUFFERSIZE
Property name for the console buffer size.- See Also:
PROP_DISPLAYONSCREENLEVEL
Property name for the minimum log level displayed on screen.- See Also:
PROP_DEFAULTLEVEL
Property name for the default log level.- See Also:
PROP_GROUP_READABLE
Property name for group-readable (660) log files. When enabled, the current log and rotated .gz files are readable/writable by the group the router runs under, so sysadmins who are members of that group can inspect the logs. The files are never world-readable.- See Also:
PROP_LOG_BUFFER_SIZE
Config key for the log buffer size.- See Also:
PROP_DROP
Config key to drop messages on buffer overflow.- See Also:
PROP_DUP
Config key for dropping duplicate messages.- See Also:
PROP_FLUSH
Config key for the log flush interval.- See Also:
PROP_GZIP
PROP_MIN_GZIP_SIZE
Config key for the minimum log size to gzip.- See Also:
PROP_RECORD_PREFIX
Prefix for per-logger level override properties.- See Also:
DEFAULT_FORMAT
Default log record format string.- See Also:
DEFAULT_DATEFORMAT
Date pattern used when none is configured.- See Also:
DEFAULT_FILENAME
Default log file name pattern.- See Also:
DEFAULT_FILESIZE
Default log file size limit as a string.- See Also:
DEFAULT_DISPLAYONSCREEN
public static final boolean DEFAULT_DISPLAYONSCREENDefault setting for on-screen log display.- See Also:
DEFAULT_CONSOLEBUFFERSIZE
public static final int DEFAULT_CONSOLEBUFFERSIZEDefault number of entries in the console buffer.- See Also:
DEFAULT_ROTATIONLIMIT
Default log rotation limit.- See Also:
DEFAULT_DEFAULTLEVEL
Default log level string.- See Also:
DEFAULT_ONSCREENLEVEL
Default on-screen log level string.- See Also:
MIN_FILESIZE_LIMIT
private static final int MIN_FILESIZE_LIMITSmallest log file size allowed.- See Also:
DEFAULT_GZIP
private static final boolean DEFAULT_GZIPDefault for compressing the rotated logs.- See Also:
DEFAULT_MIN_GZIP_SIZE
private static final int DEFAULT_MIN_GZIP_SIZEDefault smallest log size to compress.- See Also:
_context
The app context._log
Logger for the log manager itself._configLastRead
private long _configLastReadWhen was the config file last read (or -1 if never)._locationFile
The config file.MAX_BUFFER
private static final int MAX_BUFFERMax LogRecords to buffer in memory before we start blocking.- See Also:
_records
Ordered list of LogRecord elements that have not been written out yet._limits
_logs
String (scope) or Log.LogScope to Log object._writer
Who clears and writes our records. Volatile so the writer started here is safely published to the callers that read the field without holding this object's monitor._shutdown
private volatile boolean _shutdownTrue once the manager has shut down._defaultLimit
private volatile int _defaultLimitDefault log level for logs that aren't explicitly controlled through a LogLimit in _limits._format
private volatile char[] _formatLog record format string._dateFormat
Date format instance._dateFormatPattern
Date format string (for the SimpleDateFormat instance)._baseLogfilename
Log filename pattern._fileSize
private volatile int _fileSizeMax bytes in the logfile before rotation._rotationLimit
private int _rotationLimitMax rotated logs._onScreenLimit
private volatile int _onScreenLimitMinimum log level to be displayed on stdout._displayOnScreen
private volatile boolean _displayOnScreenWhether or not we even want to display anything on stdout._consoleBufferSize
private int _consoleBufferSizeHow many records we want to buffer in the "recent logs" list._consoleBuffer
The actual "recent logs" list._logBufferSize
private int _logBufferSizeSize of the in memory log buffer._dropOnOverflow
private volatile boolean _dropOnOverflowTrue to drop records when the buffer is full._dropDuplicates
private boolean _dropDuplicatesTrue to drop repeated records._droppedRecords
Records dropped since startup._flushInterval
private int _flushIntervalFlush interval of the writers, in seconds._gzip
private volatile boolean _gzipTrue to compress the rotated logs._minGzipSize
private long _minGzipSizeSmallest rotated log that gets compressed._alreadyNoticedMissingConfig
private boolean _alreadyNoticedMissingConfigTrue once the missing config file was logged.
Constructor Details
LogManager
Create the log manager for the given context.- Parameters:
context- the I2P app context
Method Details
startLogWriter
private void startLogWriter()Start the log writer thread, if it isn't running already. Synchronized so only one writer is started; the field itself is volatile because the threads that use the writer do not hold this monitor.getLog
getLog
getLog
Log for the given class and name, creating it if necessary.- Parameters:
cls- the class (may be null)name- the scope suffix, or null to scope the log by class name alone- Returns:
- the shared Log instance for that class and scope, created if it does not exist yet
getLogs
addLog
If the log already exists, its priority is set here but cannot be changed later, as it becomes an "orphan" not tracked by the manager.- Parameters:
log- the Log to add and track
getBuffer
Return the circular buffer holding recent log records for console display.- Returns:
- the console buffer
displayOnScreen
public boolean displayOnScreen()Whether log messages should be printed to stdout.- Returns:
- whether to display log on screen
getDisplayOnScreenLevel
public int getDisplayOnScreenLevel()Minimum log level for messages printed to stdout.- Returns:
- the minimum level for on-screen display
getConsoleBufferSize
public int getConsoleBufferSize()Maximum number of entries held in the console buffer.- Returns:
- the console buffer size
setConfig
Configure the logger from the given config file, reloading the configuration.- Parameters:
filename- the config file path
currentFile
File may not exist or have old logs in it if not opened yet.- Returns:
- non-null
addRecord
Used by Log to add records to the queue. This is generally nonblocking and unsyncrhonized but may block when under massive logging load as a way of throttling logging threads.- Parameters:
record- the log record to enqueue
rereadConfig
void rereadConfig()Called periodically by the LogWriter thread to reload the config file. Do not log here, deadlock of LogWriter.shouldDropDuplicates
boolean shouldDropDuplicates()Whether duplicate log records should be dropped.- Returns:
- true if duplicate records are dropped
loadConfig
private void loadConfig()Load and parse the logger configuration file if it has changed. Do not log here, deadlock of LogWriter via rereadConfig().parseConfig
Parse all configuration properties and set internal state accordingly. Do not log here, deadlock of LogWriter via rereadConfig().- Parameters:
config- the configuration properties to parse
parseLimits
Do not log here, deadlock of LogWriter via rereadConfig().- Parameters:
config- the properties to read the log limits from, may be null
parseLimits
Do not log here, deadlock of LogWriter via rereadConfig().- Parameters:
config- the properties to read the log limits from, may be nullrecordPrefix- required key prefix, stripped before matching; null for any key
setLimits
Update the existing limit overrides.- Parameters:
limits- mapping of prefix to log level string (not the log #)
setDateFormat
Update the date format Do not log here, deadlock of LogWriter via rereadConfig().- Parameters:
format- null or empty string means use default format for the locale (with a SHORT date and a MEDIUM time - seeDateFormat)- Returns:
- true if the format was updated, false if it was invalid
setFileSize
public void setFileSize(int numBytes) Update the log file size limit.- Parameters:
numBytes- the requested limit in bytes, raised to the 16 KiB minimum; zero or negative is ignored
getDefaultLimit
Default limit for logs without explicit overrides, as a text string.- Returns:
- the default log limit as a string
setDefaultLimit
Configure the default log limit from a text string.- Parameters:
lim- the default log limit string
getLimits
Return a mapping of the explicit overrides - path prefix to (text formatted) limit.- Returns:
- the explicit overrides, keyed by path prefix, with text-formatted limits
getFileSize
Determine how many bytes are in the given formatted string (5m, 60g, 100k, etc) Size may be k, m, or g. A trailing b is ignored. Upper-case is allowed. Spaces between the number and letter is are allowed. The number may be in floating point. 16K min, 2 GB max (returns int).- Parameters:
size- the formatted size to parse, such as "5m", "60g" or "100k"- Returns:
- the file size
updateLimits
private void updateLimits()Do not log here, deadlock of LogWriter via rereadConfig().updateLimit
Do not log here, deadlock of LogWriter via rereadConfig().- Parameters:
log- the log to apply the longest matching limit to
getLimits
getBaseLogfilename
Base log filename pattern.- Returns:
- the pattern with the substitutions unexpanded
setBaseLogfilename
Configure the base log filename pattern.- Parameters:
filenamePattern- the base log filename pattern
getFileSize
public int getFileSize()Maximum log file size in bytes before rotation.- Returns:
- the maximum log file size in bytes
getRotationLimit
public int getRotationLimit()Number of rotated log files to keep.- Returns:
- the rotation limit (number of log files to keep)
shouldGzip
public boolean shouldGzip()Check if gzip compression should be used for rotated log files.- Returns:
- true if rotated log files should be gzip compressed
setGzip
public void setGzip(boolean yes) Enable or disable gzip compression for rotated log files.- Parameters:
yes- true to enable gzip compression
getMinGzipSize
long getMinGzipSize()Minimum size for gzip compression.- Returns:
- the minimum size in bytes, or Long.MAX_VALUE if gzip is disabled
saveConfig
public boolean saveConfig()Save the current logging configuration to disk.- Returns:
- true if the configuration was saved successfully
createConfig
Writes the default logging configuration.- Returns:
- the properties written
getQueue
getFormat
public char[] getFormat()Log format characters.- Returns:
- the format, as a character array
setFormat
public void setFormat(char[] fmt) Configure the log format characters.- Parameters:
fmt- the log format characters
getDateFormat
Any usage of returned formatter must be synchronized!- Returns:
- the date format
getDateFormatPattern
Date format pattern string.- Returns:
- the pattern used for the log dates
flush
shutdown
public void shutdown()Shut down the log manager, flushing and stopping the writer.getContext
I2PAppContext getContext()Convenience method for LogRecordFormatter.- Returns:
- the router context this LogManager was created in