Skip to content
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

Add file documentation and project source of log4j2. #22

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
153 changes: 153 additions & 0 deletions log4j2/docs/log4j2-tutorial.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
# 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.
alexJava2015 marked this conversation as resolved.
Show resolved Hide resolved
* 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'
## Configuración
### Ecosistema
alexJava2015 marked this conversation as resolved.
Show resolved Hide resolved
* Existen diversas herramientas para la administración de proyectos, con tipos de instalación tradicional como: Maven, Gradle, Ivy, etc.
Copy link
Owner

Choose a reason for hiding this comment

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

¿cuál es la idea de la primer viñeta en relación con la segunda? Al leerlas genera la impresión que una no tiene que ver con la otra..

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 mueve esta sección a otro módulo

* Para esta versión se tienen diversas `appenders` para poder configurar la bitácora de una manera más clara y consciza, a continucación se listan algunos:
alexJava2015 marked this conversation as resolved.
Show resolved Hide resolved
1. CouchDB
2. MongoDB
3. Cassandra
4. IO Streams
5. Scala API
* En la siguiente liga se encuentrar la configuración tradicional y appenders mencionados en el punto anterior: https://logging.apache.org/log4j/2.x/maven-artifacts.html
Copy link
Owner

Choose a reason for hiding this comment

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

typo:
encontrar -> encuentra

### Archivo de configuración o implementación
Copy link
Owner

Choose a reason for hiding this comment

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

Falta numeración

* Existen diversos formatos para realizar la configuración de Log4J :
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 que es aplicada en caso de no encontrar archivos de configuración.
Copy link
Owner

Choose a reason for hiding this comment

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

Aquí vale la pena documentar las configuraciones que se toman por default, justamente cuando no se encuentran los archivos. Por ejemplo, el nivel de logging es INFO, etc...

* Log4J2 define la clase `ConfigurationFactory` encargada de detectar la presencia de archivos de configuración con base a las siguientes reglas:
Copy link
Owner

Choose a reason for hiding this comment

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

Según recuerdo, esta reglas se ejecutan en el orden de esta lista. De ser así, vale la pena mencionarlo en la explicación.

1. Se intenta ubicar el archivo especificado por una JVM system property: `log4j.configurationFile`
2. En caso de no existir el archivo especificado en el punto anterior, la clase `ConfigurationFactory` buscará `log4j2-test.properties` in the classpath.
Copy link
Owner

Choose a reason for hiding this comment

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

¿in the classpath? ¿spanglish? evita hacer copy & paste de la documentación. Traducir esta parte. Revisar toda la lista ya que aparece varias veces.

3. En caso de no existir el archivo especificado en el punto anterior, la clase `ConfigurationFactory` buscará `log4j2-test.yaml` o `log4j2-test.yml` in the classpath.
4. En caso de no existir el archivo especificado en el punto anterior, la clase `ConfigurationFactory` buscará `log4j2-test.json` o `log4j2-test.jsn` in the classpath.
5. En caso de no existir el archivo especificado en el punto anterior, la clase `ConfigurationFactory` buscará `log4j2-test.xml` in the classpath.
6. En caso de no existir el archivo especificado en el punto anterior, la clase `ConfigurationFactory` buscará `log4j2.properties` in the classpath.
7. En caso de no existir el archivo especificado en el punto anterior, la clase `ConfigurationFactory` buscará `log4j2.yaml` o `log4j2.yml` in the classpath.
8. En caso de no existir el archivo especificado en el punto anterior, la clase `ConfigurationFactory` buscará `log4j2.json` o `log4j2.jsn`.
9. En caso de no existir el archivo especificado en el punto anterior, la clase, `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.

### Configurando Log4J2 a través de un archivo properties.
* Agregar archivo log4j2.properties en la ruta: `/src/main/resources`
Copy link
Owner

Choose a reason for hiding this comment

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

Falta numeración...
Los nombres de los archivos también deben ir en comillas simples invertidas: log4j2.properties

```bash
Copy link
Owner

Choose a reason for hiding this comment

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

Aquí falta agregar una línea que diga que el siguiente código es un ejemplo. Agregar la siguiente línea:

Ejemplo:

Por otro lado, este ejemplo es un archivo properties. Entonces no debes usar bash debes emplear properties .Esto permite que el editor agregue colorcitos al ejemplo y se pueda leer mejor.
Finalmente, antes de presentar el ejemplo, considero que hace falta una pequeña explicación general que describa al archivo. Por ejemplo, mencionar que este ejemplo contiene las propiedades mínimas o básicas recomendadas, etc..

#Nivel de eventos Log4j internos que deben registrarse en la consola.
#Se recomienda poner debug para mostrar el comportamiento de un aplicativo ya que manda a consola registro de
lo que sucede incluso antes de encontrar el archivo "properties", util para encontrar errores de inicialización.
#Posibles valores: "trace", "debug", "info", "warn", "error" and "fatal"
status=debug
Copy link
Owner

Choose a reason for hiding this comment

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

Sorry. No entendí estos comentarios. No me quedó claro que significa el property status Podrías ser más corto y conciso en tu explicación ?


#File name. "Optional"
Copy link
Owner

Choose a reason for hiding this comment

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

Mejorar el comentario.. Debes escribir una descripción breve y clara del significado de cada property.

name = PropertiesConfig

#Path log file
Copy link
Owner

Choose a reason for hiding this comment

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

Mejorar comentario.

property.filename = logs/logExample

#Type appender, this can be console, file, rolling, etc.
Copy link
Owner

Choose a reason for hiding this comment

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

Mejorar comentario y en español.

appenders = console, file

## File configuration section
#FileAppender to initialize configuration
Copy link
Owner

Choose a reason for hiding this comment

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

Mejorar comentario.

appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/log4j2
appender.file.layout.type=PatternLayout

# Specify the pattern of the logs
Copy link
Owner

Choose a reason for hiding this comment

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

Creo que sería bueno explicar a nivel general el significado de cada pattern. SI es demasiado podrías solo indicar que se va a revisar más adelante. O si de plano es mucha documentación, entonces poner una liga donde se pueda consultar.

appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

#Configuration to writte in file
Copy link
Owner

Choose a reason for hiding this comment

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

Mejorar comentario.

loggers=file
logger.file.name=log4j2.HelloWorldLog4j2
logger.file.level = info
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE


## Console configuration section
# ConsoleAppender to initialize configurations
Copy link
Owner

Choose a reason for hiding this comment

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

Mejorar comentario. Valdría la pena indicar posibles tipos de consolas.. o las distintas opciones que se pueden emplear.

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout

# Specify the pattern of the logs
Copy link
Owner

Choose a reason for hiding this comment

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

¿ por qué otra vez un patrón de formato ?
Debido a que este es tu primer ejemplo, creo que debería contener solo lo mínimo o básico. Ya mas adelante puedes explicar cosas mas avanzadas.

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

#Configuration appender type, in this case show logs in console
Copy link
Owner

Choose a reason for hiding this comment

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

Mejorar comentario.

rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

#Level of events that belong to a class
rootLogger.level = info
#In addition it can configure in code, the equivalent values of level are:
Copy link
Owner

Choose a reason for hiding this comment

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

¿explicación en inglés? Evita copy & paste.
¿ qué son esos números que aparecen después de los niveles... 100, 200, etc ?

# OFF 0
# FATAL 100
# ERROR 200
# WARN 300
# INFO 400
# DEBUG 500
# TRACE 600
# ALL Integer.MAX_VALUE
```
* 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 LogManager
* Es una clase java con características especiales para log4j2.
* Esta clase es usada por el usuario de la aplicación para crear las instancias de logger.
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 "Instancias del logger" ? no sería mejor indicar el nombre de la clase de donde salen las instancias ? Procura mejorar redacción. No seas tan técnico. Piensa que es un tutorial Por ejemplo:
La clase LogManager representa el punto de entrada para crear instancias de xxxxx.... algo así.

* 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.

* Define la configuración que es aplicada por default.
* 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 de la aplicación, no es posible modificarla posteriormente.
* 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.

* 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 HelloWorldLog4j2 {

private static final Logger logger = LogManager.getLogger(HelloWorldLog4j2.class.getName());

public static void main(String[] args) {
logger.info("This Will Be Printed On Info");
logger.debug("This Will Be Printed On Debug");
logger.warn("This Will Be Printed On Warn");
logger.error("This Will Be Printed On Error");
logger.fatal("This Will Be Printed On Fatal");
logger.info("Appending string: {}.", "Hello, World");
}
```
Fin de modulo
Copy link
Owner

Choose a reason for hiding this comment

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

Te faltan los gatos:

Fin de módulo.

Revisa el formato de otros tutos.

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.

Supongo que habrá más módulos vdd ? este primer PR solo contiene un Ejemplo básico. Recomiendo renombrar el archivo md a modulo01.md y procura que tu PR tenga un título más adecuado, por ejemplo: tutorial log4j2 - modulo 1.
Hay muchas funcionalidades que vale la pena documentar: expresiones lambda, desempeño, etc,



30 changes: 30 additions & 0 deletions log4j2/example-log4j2/.classpath
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
Copy link
Owner

Choose a reason for hiding this comment

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

Quedamos en que ibas a eliminar este archivo. ¿ no funciona si lo quitas ?

<classpath>
<classpathentry kind="src" output="bin/main" path="src/main/java">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/main" path="src/main/resources">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/java">
<attributes>
<attribute name="gradle_scope" value="test"/>
<attribute name="gradle_used_by_scope" value="test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/resources">
<attributes>
<attribute name="gradle_scope" value="test"/>
<attribute name="gradle_used_by_scope" value="test"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>
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
23 changes: 23 additions & 0 deletions log4j2/example-log4j2/.project
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
alexJava2015 marked this conversation as resolved.
Show resolved Hide resolved
<projectDescription>
<name>examples-log4j2</name>
<comment>Project log4j2 created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
</projectDescription>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
connection.project.dir=
Copy link
Owner

Choose a reason for hiding this comment

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

Mismo caso, Quedamos en que ibas a eliminar este archivo. ¿ no funciona si lo quitas ?

eclipse.preferences.version=1
4 changes: 4 additions & 0 deletions log4j2/example-log4j2/.settings/org.eclipse.jdt.core.prefs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
eclipse.preferences.version=1
alexJava2015 marked this conversation as resolved.
Show resolved Hide resolved
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.source=1.8
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
Loading