Skip to content

Commit 3088609

Browse files
committed
Improve Android example
1 parent 98968fd commit 3088609

File tree

5 files changed

+73
-69
lines changed

5 files changed

+73
-69
lines changed

log4j-samples-android/app/build.gradle

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,6 @@ dependencies {
5959
androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1'
6060

6161
//Log4j
62-
implementation 'org.apache.logging.log4j:log4j-api:2.24.1'
63-
implementation 'org.apache.logging.log4j:log4j-core:2.24.1'
62+
implementation 'org.apache.logging.log4j:log4j-api:2.25.0-SNAPSHOT'
63+
implementation 'org.apache.logging.log4j:log4j-core:2.25.0-SNAPSHOT'
6464
}

log4j-samples-android/app/src/main/java/org/apache/logging/log4j/samples/android/MainActivity.java

Lines changed: 46 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -16,91 +16,84 @@
1616
*/
1717
package org.apache.logging.log4j.samples.android;
1818

19-
import androidx.appcompat.app.AlertDialog;
20-
import androidx.appcompat.app.AppCompatActivity;
21-
22-
import android.os.Bundle;
23-
import android.widget.Button;
24-
import android.widget.TextView;
19+
import java.util.Arrays;
20+
import java.util.HashMap;
21+
import java.util.List;
22+
import java.util.Map;
2523

2624
import org.apache.logging.log4j.Level;
2725
import org.apache.logging.log4j.LogManager;
2826
import org.apache.logging.log4j.Logger;
2927
import org.apache.logging.log4j.core.config.Configurator;
3028

31-
import java.util.Arrays;
29+
import android.os.Bundle;
30+
import android.view.View;
31+
import android.widget.Button;
32+
import android.widget.TextView;
33+
import androidx.appcompat.app.AlertDialog;
34+
import androidx.appcompat.app.AppCompatActivity;
3235

3336
public class MainActivity extends AppCompatActivity {
3437

35-
private int logLevelIdx;
38+
private static final Logger logger = LogManager.getLogger(MainActivity.class);
39+
private static final int[] buttonIds = {
40+
R.id.fatalLogBtn, R.id.errorLogBtn, R.id.warnLogBtn, R.id.infoLogBtn, R.id.debugLogBtn, R.id.traceLogBtn
41+
};
42+
/**
43+
* All log levels
44+
*/
45+
private static final List<Level> logLevels = Arrays.asList(
46+
Level.OFF, Level.FATAL, Level.ERROR, Level.WARN, Level.INFO, Level.DEBUG, Level.TRACE, Level.ALL);
3647

37-
//Logger log = LogManager.getLogger(MainActivity.class);
38-
Logger log = LogManager.getRootLogger();
48+
private int logLevelIdx;
49+
private final Map<View, Level> buttonToLevel = new HashMap<>();
3950

4051
@Override
4152
protected void onCreate(Bundle savedInstanceState) {
4253
super.onCreate(savedInstanceState);
54+
logger.info("Creating Main Activity...");
4355
setContentView(R.layout.activity_main);
4456

45-
/*// Manually read in log4j2.properties
46-
LoggerContext context = (LoggerContext) LogManager.getContext(false);
47-
try {
48-
InputStream inputStream = getAssets().open("log4j2.properties");
49-
ConfigurationSource source = new ConfigurationSource(inputStream);
50-
context.start(ConfigurationFactory.getInstance().getConfiguration(context, source));
51-
} catch (IOException e) {
52-
e.printStackTrace();
53-
}*/
54-
55-
/*// Explicitly set the logging level for this logger to INFO
56-
//Configurator.setLevel(log, Level.INFO);
57-
LoggerConfig loggerConfig = context.getConfiguration().getLoggerConfig(log.getName());
58-
loggerConfig.setLevel(Level.INFO);*/
59-
60-
//
61-
// UI bindings
62-
//
63-
//TextView displaying Log Level
57+
// TextView displaying Log Level
6458
TextView logLevelTxt = findViewById(R.id.logLevelTxt);
65-
logLevelTxt.setText(log.getLevel().name());
59+
logLevelTxt.setText(logger.getLevel().name());
6660

67-
//Change log level
61+
// Change log level
6862
Button setLogLevelBtn = findViewById(R.id.setLogLevelBtn);
6963
setLogLevelBtn.setOnClickListener(v -> {
7064
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
7165
alertDialog.setTitle("Set log level");
7266

73-
String[] logLevels = new String[]{"OFF", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", "ALL"};
74-
logLevelIdx = Arrays.asList(logLevels).indexOf(log.getLevel().name());
67+
logLevelIdx = logLevels.indexOf(logger.getLevel());
7568

76-
alertDialog.setSingleChoiceItems(logLevels, logLevelIdx, (dialog, which) -> logLevelIdx = which);
69+
alertDialog.setSingleChoiceItems(
70+
logLevels.stream().map(Level::name).toArray(String[]::new),
71+
logLevelIdx,
72+
(dialog, which) -> logLevelIdx = which);
7773
alertDialog.setPositiveButton("Select", (dialog, which) -> {
78-
Configurator.setLevel(log, Level.valueOf(Arrays.asList(logLevels).get(logLevelIdx)));
79-
logLevelTxt.setText(log.getLevel().name());
74+
Configurator.setLevel(logger, logLevels.get(logLevelIdx));
75+
logLevelTxt.setText(logger.getLevel().name());
8076
dialog.dismiss();
8177
});
8278
alertDialog.setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());
8379
alertDialog.create();
8480
alertDialog.show();
8581
});
8682

87-
//Log messages
88-
Button fatalLogBtn = findViewById(R.id.fatalLogBtn);
89-
fatalLogBtn.setOnClickListener(v -> log.fatal("Current log level is: " + log.getLevel().name()));
90-
91-
Button errorLogBtn = findViewById(R.id.errorLogBtn);
92-
errorLogBtn.setOnClickListener(v -> log.error("Current log level is: " + log.getLevel().name()));
93-
94-
Button warnLogBtn = findViewById(R.id.warnLogBtn);
95-
warnLogBtn.setOnClickListener(v -> log.warn("Current log level is: " + log.getLevel().name()));
96-
97-
Button infoLogBtn = findViewById(R.id.infoLogBtn);
98-
infoLogBtn.setOnClickListener(v -> log.info("Current log level is: " + log.getLevel().name()));
99-
100-
Button debugLogBtn = findViewById(R.id.debugLogBtn);
101-
debugLogBtn.setOnClickListener(v -> log.debug("Current log level is: " + log.getLevel().name()));
83+
// Log messages
84+
for (int i = 0; i < buttonIds.length; i++) {
85+
Button button = findViewById(buttonIds[i]);
86+
// The `OFF` level should not have a button
87+
buttonToLevel.put(button, logLevels.get(i + 1));
88+
button.setOnClickListener(this::onLevelButtonClick);
89+
}
90+
logger.info("Main Activity created.");
91+
}
10292

103-
Button traceLogBtn = findViewById(R.id.traceLogBtn);
104-
traceLogBtn.setOnClickListener(v -> log.trace("Current log level is: " + log.getLevel().name()));
93+
void onLevelButtonClick(View view) {
94+
Level level = buttonToLevel.get(view);
95+
if (level != null) {
96+
logger.log(level, "Hello {}!", level);
97+
}
10598
}
10699
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#
2+
# Licensed to the Apache Software Foundation (ASF) under one or more
3+
# contributor license agreements. See the NOTICE file distributed with
4+
# this work for additional information regarding copyright ownership.
5+
# The ASF licenses this file to you under the Apache License, Version 2.0
6+
# (the "License"); you may not use this file except in compliance with
7+
# the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
#
17+
##
18+
log4j2.debug = true
19+
log4j2.contextSelector = org.apache.logging.log4j.core.selector.BasicContextSelector

log4j-samples-android/app/src/main/assets/log4j2.properties renamed to log4j-samples-android/app/src/main/resources/log4j2.properties

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,15 @@
1515
# limitations under the License.
1616
#
1717
##
18-
# Root logger configuration
19-
status = error
20-
name = PropertiesConfig
21-
2218
# Appenders
2319
appender.console.type = Console
24-
appender.console.name = Console
25-
appender.console.target = SYSTEM_OUT
20+
appender.console.name = CONSOLE
2621
appender.console.layout.type = PatternLayout
2722
appender.console.layout.pattern = [%d{yyyy-MM-dd HH:mm:ss.SSS}] %-5p- %m%n
2823

29-
# Root logger level and appenders
24+
# Loggers
3025
rootLogger.level = INFO
31-
rootLogger.appenderRefs = stdout
32-
rootLogger.appenderRef.stdout.ref = Console
26+
rootLogger.appenderRef.stdout.ref = CONSOLE
3327

34-
logger.com.example.log4japi.MainActivity.name = com.example.log4japi.MainActivity
35-
logger.com.example.log4japi.MainActivity.level = DEBUG
36-
logger.com.example.log4japi.MainActivity.additivity = false
37-
logger.com.example.log4japi.MainActivity.appenderRefs = stdout
38-
logger.com.example.log4japi.MainActivity.appenderRef.stdout.ref = Console
28+
logger.0.name = org.apache.logging.log4j.samples.android.MainActivity
29+
logger.0.level = DEBUG

log4j-samples-android/settings.gradle

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ dependencyResolutionManagement {
2626
repositories {
2727
google()
2828
mavenCentral()
29+
mavenLocal()
2930
}
3031
}
3132
rootProject.name = "Log4jAPI"

0 commit comments

Comments
 (0)