-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLog4jConfigurator.m
207 lines (191 loc) · 8.56 KB
/
Log4jConfigurator.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
classdef Log4jConfigurator
% A configurator for log4j
%
% This class configures the logging setup for Matlab/SLF4M logging. It
% configures the log4j library that SLF4M logging sits on top of. (We use log4j
% because it ships with Matlab.)
%
% This class is provided as a convenience. You can also configure SLF4M logging
% by directly configuring log4j using its normal Java interface.
%
% SLF4M does not automatically configure log4j. You must either call a
% configureXxx method on this class or configure log4j directly yourself to get
% logging to work. Otherwise, you may get warnings like this at the console:
%
% log4j:WARN No appenders could be found for logger (unknown).
% log4j:WARN Please initialize the log4j system properly.
%
% If that happens, it means you need to call
% logger.Log4jConfigurator.configureBasicConsoleLogging.
%
% This also provides a log4j configuration GUI that you can launch with
% `logger.Log4jConfigurator.showGui`.
%
% Examples:
%
% logger.Log4jConfigurator.configureBasicConsoleLogging
%
% logger.Log4jConfigurator.setLevels({'root','DEBUG'});
%
% logger.Log4jConfigurator.setLevels({
% 'root' 'INFO'
% 'net.apjanke.logger.swing' 'DEBUG'
% });
%
% logger.Log4jConfigurator.prettyPrintLogConfiguration
%
% % Display fully-qualified class/category names in the log output:
% logger.Log4jConfigurator.setRootAppenderPattern(...
% ['%d{HH:mm:ss.SSS} %p %c - %m' sprintf('\n')]);
%
% % Bring up the configuration GUI
% logger.Log4jConfigurator.showGui
% This class does *not* use the implicit initializer trick, because the
% implicit library initializer depends on this class!
methods (Static)
function configureBasicConsoleLogging
% Configures log4j to do basic logging to the console
%
% This sets up a basic log4j configuration, with log output going to the
% console, and the root logger set to the INFO level.
%
% This method can safely be called multiple times. If there's already an
% appender on the root logger (indicating logging has already been
% configured), it silently does nothing.
rootLogger = org.apache.log4j.Logger.getRootLogger();
rootAppenders = rootLogger.getAllAppenders();
isConfiguredAlready = rootAppenders.hasMoreElements;
if ~isConfiguredAlready
org.apache.log4j.BasicConfigurator.configure();
rootLogger = org.apache.log4j.Logger.getRootLogger();
rootLogger.setLevel(org.apache.log4j.Level.INFO);
rootAppender = rootLogger.getAllAppenders().nextElement();
% Use \n instead of %n because the Matlab console wants Unix-style line
% endings, even on Windows.
pattern = ['%d{HH:mm:ss.SSS} %-5p %c{1} %x - %m' sprintf('\n')];
myLayout = org.apache.log4j.PatternLayout(pattern);
rootAppender.setLayout(myLayout);
end
end
function setRootAppenderPattern(pattern)
% Sets the pattern on the root appender
%
% This is just a convenience method. Assumes there is a single
% appender on the root logger.
rootLogger = org.apache.log4j.Logger.getRootLogger();
rootAppender = rootLogger.getAllAppenders().nextElement();
myLayout = org.apache.log4j.PatternLayout(pattern);
rootAppender.setLayout(myLayout);
end
function out = getLog4jLevel(levelName)
% Gets the log4j Level enum for a named level
validLevels = {'OFF' 'FATAL' 'ERROR' 'WARN' 'INFO' 'DEBUG' 'TRACE' 'ALL'};
levelName = upper(levelName);
if ~ismember(levelName, validLevels)
error('Invalid levelName: ''%s''', levelName);
end
out = eval(['org.apache.log4j.Level.' levelName]);
end
function setLevels(levels)
% Set the logging levels for multiple loggers
%
% logger.Log4jConfigurator.setLevels(levels)
%
% This is a convenience method for setting the logging levels for multiple
% loggers.
%
% The levels input is an n-by-2 cellstr with logger names in column 1 and
% level names in column 2.
%
% Examples:
%
% logger.Log4jConfigurator.setLevels({'root','DEBUG'});
%
% logger.Log4jConfigurator.setLevels({
% 'root' 'INFO'
% 'net.apjanke.logger.swing' 'DEBUG'
% });
for i = 1:size(levels, 1)
[logName,levelName] = levels{i,:};
logger = org.apache.log4j.LogManager.getLogger(logName);
level = logger.Log4jConfigurator.getLog4jLevel(levelName);
logger.setLevel(level);
end
end
function prettyPrintLogConfiguration(verbose)
% Displays the current log configuration to the console
%
% logger.Log4jConfigurator.prettyPrintLogConfiguration()
if nargin < 1 || isempty(verbose); verbose = false; end
function out = getLevelName(lgr)
level = lgr.getLevel();
if isempty(level)
out = '';
else
out = char(level.toString());
end
end
% Get all names first so we can display in sorted order
loggers = org.apache.log4j.LogManager.getCurrentLoggers();
loggerNames = {};
while loggers.hasMoreElements()
logger = loggers.nextElement();
loggerNames{end+1} = char(logger.getName()); %#ok<AGROW>
end
loggerNames = sort(loggerNames);
% Display the hierarchy
rootLogger = org.apache.log4j.LogManager.getRootLogger();
fprintf('Root (%s): %s\n', char(rootLogger.getName()), getLevelName(rootLogger));
for i = 1:numel(loggerNames)
logger = org.apache.log4j.LogManager.getLogger(loggerNames{i});
appenders = logger.getAllAppenders();
appenderStrs = {};
while appenders.hasMoreElements
appender = appenders.nextElement();
if isa(appender, 'org.apache.log4j.varia.NullAppender')
appenderStr = 'NullAppender';
else
appenderStr = sprintf('%s (%s)', char(appender.toString()), ...
char(appender.getName()));
end
appenderStrs{end+1} = ['appender: ' appenderStr]; %#ok<AGROW>
end
appenderList = strjoin(appenderStrs, ' ');
if ~verbose
if isempty(logger.getLevel()) && isempty(appenderList) ...
&& logger.getAdditivity()
continue
end
end
items = {};
if ~isempty(getLevelName(logger))
items{end+1} = getLevelName(logger); %#ok<AGROW>
end
if ~isempty(appenderStr)
items{end+1} = appenderList; %#ok<AGROW>
end
if ~logger.getAdditivity()
items{end+1} = sprintf('additivity=%d', logger.getAdditivity()); %#ok<AGROW>
end
str = strjoin(items, ' ');
fprintf('%s: %s\n',...
loggerNames{i}, str);
end
end
function showGui()
% Display the log4j configuration GUI
% Make sure the log4j1-config-gui JAR is on the path
libDir = fullfile(fileparts(fileparts(fileparts(mfilename('fullpath')))), ...
'lib');
jarFile = [libDir '/java/log4j1-config-gui/log4j1-config-gui-0.1.1.jar'];
jpath = javaclasspath('-all');
if ~ismember(jarFile, jpath)
javaaddpath(jarFile);
end
gui = javaObjectEDT('net.apjanke.log4j1gui.Log4jConfiguratorGui');
gui.initializeGui();
frame = gui.showInFrame();
frame.setVisible(true);
end
end
end