Skip to content

Add file documentation and project source of log4j2. #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions log4j2/docs/log4j2-tutorial.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# Log4J 2
## 1 Características
### 1.1 Introducción
* Log4j2 compatible y seguro ya que usa las mismas funcionalidades de slf4j.
* Log4j2 más extenso que slf4j.
* Log4j2 escalable porque puede soportar otras implementaciones.
* Log4j2 incluye integración mediante el módulo o puente "log4j-to-slf4j" para cambiar a slf4j cuando se requiera.
* No permite multiples implementaciones.
* Algunas de las funcionalidades de Log4j2:
* Message API
* Java 8 lambda support
* Mixing {}-style
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Traducir a español. En general, revisar esta lista. Esto parece un copy & paste de la documentación. Traduce todas las funcionalidades al español, y agrega un muy breve descripción.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Se realizó la traducción y se agrego la descripción correspondiente.

* CloseableThreadContext
* Log4j2's ThreadContext
* SLF4J does not support the FATAL log level.
* Log4j2 has support for custom log levels.
* The Log4j2 API accepts any Object, not just Strings
* The above you get for free just by using the Log4j2 API directly.
* SLF4J Markers'
## 2 Configuración de Log4j2
### 2.1 Archivo de configuración o implementación
* Existen 4 diversos tipo de configuración o implementación, tales como:
1. Json
2. Yaml
3. Xml
4. Archivo de propiedades. "fileName.properties".
* Para configurar cada una de las implementaciones visitar la liga correspondiente.
1. `Json` https://logging.apache.org/log4j/2.x/manual/configuration.html#JSON
2. `Yaml`https://logging.apache.org/log4j/2.x/manual/configuration.html#YAML
3. `Xml` https://logging.apache.org/log4j/2.x/manual/configuration.html#XML

* Log4J2 cuenta con una configuración por default si no encuentra archivo a cargar.
* Log4j2 tiene una clase llamada: `ConfigurationFactory` la cual se encarga de la configuración de las diversas implementaciones.
* `ConfigurationFactory` contiene lógica para encontrar la implementación a cargar, el orden de busqueda es el siguiente :
1. Primero buscará el archivo especificado en la propiedad: "log4j.configurationFile".
2. Si no existe el archivo `log4j.configurationFile` la clase `ConfigurationFactory` buscará `log4j2-test.properties`.
3. Si no existe el archivo anterior la clase `ConfigurationFactory` buscará `log4j2-test.yaml` o `log4j2-test.yml`.
4. Si no existe el archivo anterior la clase `ConfigurationFactory` buscará `log4j2-test.json` o `log4j2-test.jsn`.
5. Si no existe el archivo anterior la clase `ConfigurationFactory` buscará `log4j2-test.xml`
6. Sí el archivo de prueba anterior no existe `ConfigurationFactory` buscará `log4j2.properties`
7. Sí el archivo de propiedades anterior no existe `ConfigurationFactory` buscará `log4j2.yaml` o `log4j2.yml`.
8. Sí el archivo anterior no existe `ConfigurationFactory` buscará `log4j2.json` o `log4j2.jsn`.
9. Sí el archivo anterior no existe, `ConfigurationFactory` buscará `log4j2.xml`.
10. Sí no encuentra ningún archivo de configuración, se cargará el default y la salida de la traza de errores será en la consola
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

¿traza? En español no usamos esta palabra.. suena raro. Mejorar la traducción.

### 2.1.1 Configurando log4j2 con archivo de propiedades
A continuación se muestra la configuración clásica estandar de un aplicativo, si se desea cualquier otra implementación, retomar la sección 2.1.
* Agregar archivo log42.properties en la ruta: `/src/main/resources`

Datos de archivo de propiedades
```bash
status = error
name = PropertiesConfig

filters = threshold

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appenders = console

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
```
* Agregar la configuración correspondiente "anexar dependencia", para este caso de prueba usaremos la herramienta gradle.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No entendí esta oración. Es una orden ? o cuál es la idea ? Mejora redacción.


Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Antes de iniciar con la configuración de gradle, creo que vale la pena agregar una sección donde expliques la forma en la que Log4J2 se distribuye. Es decir, ahora log4J2 se distribuye en varios jars. Entonces hay que listarlos y escribir una breve explicación. En especial hacer énfasis que log4j-api contiene las clases agnósticas a la implementación y que puedes usar cualquier otra implementación.

Agregar dependencia log42:
```
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

después de las 3 comillas, agrega la palabra groovy
build.gradle tiene esta sintaxis, y así el código se ve mucho mejor.

dependencies {
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.6.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.6.1'
Copy link
Owner

@jorgerdc jorgerdc Aug 20, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

usa la forma corta:
compile "org.apache.logging.log4j:log4j-api:$log4jVersion"
Observa el uso de la variable $log4jVersion Recomiendo que agregues variables para no hardcodear valores varias veces. Revisa ejemplos en el tutorial de junit.
Ahora, para el caso del otro jar, según yo no debe ser compile, debería ser solo runtime. Esto implica que las clases del jar log4j-core no deben aparecer en el código fuente. Esto protege al código para que no se usen clases de una implementación en especifico. Es decir, quedaría así:

runtime "org.apache.logging.log4j:log4j-core:$log4jVersion"
Revisa si esta propuesta funciona.

}
```
#
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remover el símbolo de gato, y revisa la numeración. ¿realmente es el tema 2 ?

### 2.2 Descripción LogManager
* Es una clase java con características especiales para log4j2.
* Esta clase es usada por el cliente de la aplicación para solicitar las instancias de logger.
* Gestiona la configuración de logging framework, este se encarga de leer la configuración inicial que se tendra en las bitácoras de la aplicación.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

¿ a qué te refieres con logging framework??? Mejora la traducción y explicación.

* Contiene configuración default, sí no se especifica alguna en particular.
* Se puede especificar el nivel de logeo `info, debug, fatal, etc`.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No creo que sea buena idea poner etc... Menciona todos los posibles niveles. No son muchos.

* Se carga durante el inicio del aplicativo pero no se puede modificar subsecuentemente cargado.
* La configurarción se puede realizar mediante una clase java.
#
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nuevamente, debes agregar la palabra "Ejemplo:" antes de poner tu código. Revisa otros tutoriales para que veas la convención que estoy siguiendo. NO dejes solo el símbolo de gato.

### 2.3 Comprobación de configuración
* Ejecutar la siguiente clase para confirmar que la configuración anterior sea correcta.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Transforma este ejemplo en una prueba unitaria con JUnit 5. Hay que poner el ejemplo con nuestros propios tuturiales.

```bash
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HelloWorld {

private static final Logger LOGGER = LogManager.getLogger(HelloWorld.class.getName());

public static void main(String[] args) {
LOGGER.debug("Debug Message Logged !!!");
LOGGER.info("Info Message Logged !!!");
LOGGER.error("Error Message Logged !!!", new NullPointerException("NullError"));
}
}
```
* Se debe mostrar una salida en consola, como la siguiente.
```bash
2019-05-18 18:39:56 DEBUG HelloWorld:21 - Debug Message Logged !!!
2019-05-18 18:39:56 INFO HelloWorld:22 - Info Message Logged !!!
2019-05-18 18:39:56 ERROR HelloWorld:23 - Error Message Logged !!!
java.lang.NullPointerException: NullError
at log4j2.HelloWorld.main(HelloWorld.java:23) [main/:?]
```



5 changes: 5 additions & 0 deletions log4j2/example-log4j2/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Ignore Gradle project-specific cache directory
.gradle
.project
# Ignore Gradle build output directory
build
16 changes: 16 additions & 0 deletions log4j2/example-log4j2/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

plugins {
id 'java-library'
}

repositories {
jcenter()
}

dependencies {
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.6.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.6.1'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
188 changes: 188 additions & 0 deletions log4j2/example-log4j2/gradlew
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
#!/usr/bin/env sh

#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn () {
echo "$*"
}

die () {
echo
echo "$*"
echo
exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`

# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option

if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi

# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")

# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"

# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi

exec "$JAVACMD" "$@"
Loading