-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
traduccion capitulo 12, error cap 12.3
- Loading branch information
1 parent
92b8713
commit 2507b54
Showing
6 changed files
with
144 additions
and
134 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,29 +1,29 @@ | ||
# 12.1 Logs | ||
# 12.1 Registros | ||
|
||
We look forward to developing Web applications able to run the entire program of various events occurring during record each, Go language provides a simple log package, we use the package can easily achieve logging features, these log are based on the combined package fmt print function like panic for general printing, throwing error handling. Go current standard package only contains a simple function, if we want our application log to a file, and then to combine log achieve a lot of complex functions( written a Java or C++, the reader should have used log4j and log4cpp like logging tool ), you can use third-party developers a logging system, `https://github.com/cihub/seelog`, which implements a very powerful logging functions. Next, we describe how the system through the log to achieve our application log function. | ||
Esperamos con interés el desarrollo de aplicaciones web capaces de ejecutar todo el programa de varios eventos que ocurren durante cada registro, Go lenguaje proporciona un paquete de registro simple, utilizando el paquete puede conseguir fácilmente las funciones de registro, registro de éstos se basan en la función de impresión del paquete fmt combinado como el pánico para la impresión en general, lanzando el tratamiento de errores. Vaya paquete estándar actual sólo contiene una función simple, si queremos que nuestro registro de aplicación en un archivo, y luego combinar registramos lograr una gran cantidad de funciones complejas (escrito un Java o C + +, el lector debería haber utilizado log4j y log4cpp como herramienta de registro) , puede utilizar los desarrolladores de terceros un sistema de registro, https://github.com/cihub/seelog , que implementa un medio muy poderoso funciones de registro. A continuación, se describe cómo el sistema a través del registro de alcanzar nuestra función de registro de aplicación. | ||
|
||
## Seelog Introduction | ||
## Seelog Introducción | ||
|
||
seelog with Go language of a logging system, it provides some simple function to implement complex log distribution, filtering, and formatting. Has the following main features: | ||
seelog con Go lenguaje de un sistema de registro, que proporciona una función simple de implementar la distribución compleja de registro, el filtrado y formateo. Tiene las siguientes características principales: | ||
|
||
- XML dynamic configuration, you can not recompile the program and dynamic load configuration information | ||
- Supports hot updates, the ability to dynamically change the configuration without the need to restart the application | ||
- Support multi- output stream that can simultaneously output the log to multiple streams, such as a file stream, network flow, etc. | ||
- Support for different log output | ||
- Configuración dinámica de XML, no se puede volver a compilar el programa y la información de configuración de carga dinámica | ||
- Soporta actualizaciones calientes, la capacidad de cambiar de forma dinámica la configuración sin la necesidad de reiniciar la aplicación | ||
- Apoyo de múltiples flujos de salida que puede simultáneamente en la salida del registro de corrientes múltiples, como una secuencia de archivo, el flujo de la red, etc | ||
- Apoyo a la salida del registro diferente | ||
|
||
- Command line output | ||
- File Output | ||
- Cached output | ||
- Support log rotate | ||
- SMTP Mail | ||
- Salida de línea de comandos | ||
- Archivo de salida | ||
- Salida en caché | ||
- Soporte de registro de rotación | ||
- Correo SMTP | ||
|
||
The above is only a partial list of features, seelog is a particularly powerful log processing systems, see the detailed contents of the official wiki. Next, I will briefly describe how to use it in your project: | ||
Lo anterior es sólo una lista parcial de las características, seelog es particularmente potentes sistemas de procesamiento de registro, ver el contenido detallado de la wiki oficial. A continuación, voy a describir brevemente cómo usarlo en su proyecto: | ||
|
||
First install seelog | ||
Primero instale seelog | ||
|
||
go get -u github.com/cihub/seelog | ||
|
||
Then we look at a simple example: | ||
Entonces nos fijamos en un ejemplo sencillo: | ||
|
||
package main | ||
|
||
|
@@ -35,11 +35,11 @@ Then we look at a simple example: | |
} | ||
|
||
|
||
When compiled and run if there is a `Hello from seelog`, description seelog logging system has been successfully installed and can be a normal operation. | ||
Cuando se compila y ejecuta si hay una Hello from seelog , sistema de registro de descripción seelog se ha instalado correctamente y puede ser un funcionamiento normal. | ||
|
||
## Based seelog custom log processing | ||
## Procesamiento de registro personalizado seelog base | ||
|
||
seelog support custom log processing, the following is based on its custom log processing part of the package: | ||
apoyo seelog procesamiento de registro personalizado, el siguiente se basa en su parte de procesamiento de registro personalizado del paquete: | ||
|
||
|
||
package logs | ||
|
@@ -85,43 +85,45 @@ seelog support custom log processing, the following is based on its custom log p | |
loadAppConfig() | ||
} | ||
|
||
// DisableLog disables all library log output | ||
//DisableLog desactiva todas las salidas del registro de la biblioteca | ||
func DisableLog() { | ||
Logger = seelog.Disabled | ||
} | ||
|
||
// UseLogger uses a specified seelog.LoggerInterface to output library log. | ||
// Use this func if you are using Seelog logging system in your app. | ||
// UseLogger utiliza un seelog.LoggerInterface especificada en el registro de la biblioteca de salida. | ||
// Utilice esta función si está utilizando el sistema de registro Seelog en su aplicación. | ||
func UseLogger(newLogger seelog.LoggerInterface) { | ||
Logger = newLogger | ||
} | ||
|
||
|
||
Above the main achievement of the three functions, | ||
Sobre el principal logro de las tres funciones, | ||
|
||
- `DisableLog` | ||
|
||
Logger initialize global variables as seelog disabled state, mainly in order to prevent the Logger was repeatedly initialized | ||
Logger inicializar variables globales como estado deshabilitado seelog, principalmente con el fin de evitar que el registrador fue inicializado en repetidas ocasione | ||
|
||
- `LoadAppConfig` | ||
|
||
Depending on the configuration file to initialize seelog configuration information, where we read the configuration file by string set up, of course, you can read the XML file. Inside the configuration is as follows: | ||
Según el archivo de configuración para inicializar la información de configuración seelog, donde leemos el archivo de configuración por la cadena de configurar, por supuesto, usted puede leer el archivo XML. Dentro de la configuración es la siguiente: | ||
|
||
- Seelog | ||
|
||
minlevel parameter is optional, if configured, is higher than or equal to the level of the log will be recorded, empathy maxlevel. | ||
MinLevel parámetro es opcional, si está configurado, es mayor que o igual al nivel de la de registro se registra, maxLevel empatía. | ||
|
||
- Outputs | ||
|
||
Output destination, where data is divided into two, one record to the log rotate file inside. Another set up a filter, if the error level is critical, it will send alarm messages. | ||
Destino de salida, donde los datos se divide en dos, un registro en el archivo de registro de rotación interior. Otra configurar un filtro, si el nivel de error es crítico, enviará mensajes de alarma. | ||
|
||
- Formats | ||
|
||
Log format defines various | ||
Formato de registro define varios | ||
|
||
- `UseLogger` | ||
|
||
Set the current logger for the corresponding log processing | ||
Configure el registrador actual para el procesamiento de registro correspondiente | ||
|
||
Above we defined a custom log processing package, the following example is to use: | ||
Arriba hemos definido un paquete de procesamiento de registro personalizado, el siguiente ejemplo es el uso de: | ||
|
||
package main | ||
|
||
|
@@ -139,36 +141,36 @@ Above we defined a custom log processing package, the following example is to us | |
logs.Logger.Critical("Server err:%v", err) | ||
} | ||
|
||
## An error occurred mail | ||
## Se ha producido un error de correo | ||
|
||
The above example explains how to set up email, we adopted the following smtp configured to send e-mail: | ||
El ejemplo anterior se explica cómo configurar el correo electrónico, se adoptó el siguiente smtp configurado para enviar e-mail: | ||
|
||
<smtp formatid="criticalemail" senderaddress="[email protected]" sendername="ShortUrl API" hostname="smtp.gmail.com" hostport="587" username="mailusername" password="mailpassword"> | ||
<recipient address="[email protected]"/> | ||
</smtp> | ||
|
||
The format of the message through criticalemail configuration, and then send messages through other configuration server configuration, configured to receive mail through the recipient user, if there are multiple users can add one line. | ||
El formato del mensaje a través de la configuración criticalemail, y luego enviar mensajes a través de otra configuración del servidor de configuración, configurado para recibir correo a través del usuario receptor, si hay varios usuarios pueden añadir una línea. | ||
|
||
To test this code is working correctly, you can add code similar to the following one false news. But remember that after should delete it, otherwise you will receive on-line after a lot of junk e-mail. | ||
Para probar este código funciona correctamente, puede agregar un código similar al siguiente noticia falsa. Pero recuerde que habían de eliminarlo, de lo contrario recibirá en línea después de una gran cantidad de correo electrónico no deseado. | ||
|
||
logs.Logger.Critical("test Critical message") | ||
|
||
Now, as long as our application online record a Critical information that you will receive an e-mail Email, so that once the online system problems, you can immediately informed by e-mail, you can timely processing. | ||
Ahora, siempre y cuando nuestra solicitud en línea grabar una información crítica que usted recibirá un e-mail al correo electrónico, de manera que una vez que los problemas en el sistema en línea, usted puede inmediatamente informado por e-mail, puede procesamiento oportuno. | ||
|
||
## Using the Application log | ||
## Utilizando el registro de la aplicación | ||
|
||
For the application logs, each person's application scenarios may vary, and some people use to do data analysis application logs, some people use the application logs do performance analysis, analysis of user behavior that some people do, and some is pure record, to facilitate the application of a problem when the auxiliary find the problem. | ||
Para los registros de aplicación, escenarios de aplicación de cada persona pueden variar, y algunas personas usan para hacer los registros de aplicaciones de análisis de datos, algunas personas utilizan los registros de la aplicación hacen análisis de rendimiento, análisis de comportamiento de los usuarios que hacen algunas personas, y algunos se registro puro para facilitar la aplicación de un problema cuando el auxiliar de encontrar el problema. | ||
|
||
As an example, we need to track a user attempts to log in the system operation. This will successful and unsuccessful attempts to record. Record the successful use of "Info" log level, rather than the successful use of "warn" level. If you want to find all unsuccessful landing, we can use the linux command tools like grep, as follows: | ||
Como ejemplo, tenemos que realizar un seguimiento de un usuario intenta iniciar sesión en el funcionamiento del sistema. Esto le intentos exitosos y fallidos de registro. Registre el uso exitoso de nivel de registro "Info", en lugar de la utilización con éxito de nivel "advertir". Si usted quiere encontrar todos aterrizaje fallido, podemos utilizar las herramientas de comando linux como grep, de la siguiente manera: | ||
|
||
# cat /data/logs/roll.log | grep "failed login" | ||
2012-12-11 11:12:00 WARN : failed login attempt from 11.22.33.44 username password | ||
|
||
In this way we can easily find the appropriate information, this will help us to do something for the application log statistics and analysis. In addition, we also need to consider the size of the log, for a high- traffic Web applications, log growth is quite terrible, so we seelog configuration files which set up logrotate, so that we can ensure that the log file will not be changing large and lead us not enough disk space can cause problems. | ||
De esta manera podemos encontrar fácilmente la información adecuada, esto ayudará a que hagamos algo para las estadísticas de registro de aplicación y análisis. Además, también tenemos que considerar el tamaño del registro, para una aplicaciones Web de alto tráfico, registro de crecimiento es bastante terrible, así que seelog archivos de configuración que establecen logrotate, por lo que podemos asegurar que el archivo de registro no será cambiando el espacio en disco no es suficientemente grande y conducirnos puede causar problemas.. | ||
|
||
## Summary | ||
## Resumen | ||
|
||
On the face of seelog system and how it can be customized based on the learning log system, and now we can easily construct a suitable demand powerful log processing the system. Data analysis log processing system provides a reliable data source, such as through the log analysis, we can further optimize the system, or application problems arise easy to find location problem, another seelog also provides a log grading function, through the configuration for min-level, we can easily set the output test or release message level. | ||
En la cara de sistema seelog y cómo puede ser personalizado basado en el sistema de registro de aprendizaje, y ahora podemos construir fácilmente una demanda potente registro adecuado de procesamiento del sistema. Sistema de procesamiento de registro de análisis de datos proporciona una fuente fiable de datos, como por ejemplo a través del análisis de registros, podemos optimizar aún más el sistema, o problemas de aplicación surgir fácil de encontrar problema de la ubicación, otro seelog también proporciona una función de clasificación de registro, a través de la configuración para min- nivel, podemos configurar fácilmente la prueba de salida o el nivel de entrega de mensajes. | ||
|
||
## Links | ||
|
||
|
Oops, something went wrong.