Updated license
[anna.git] / include / anna / core / tracing / TraceWriter.hpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_core_tracing_TraceWriter_hpp
38 #define anna_core_tracing_TraceWriter_hpp
39
40 #include <vector>
41
42 #include <anna/core/mt/NRMutex.hpp>
43 #include <anna/core/tracing/Logger.hpp>
44 #include <anna/config/defines.hpp>
45 #include <anna/core/util/Microsecond.hpp>
46
47 namespace anna {
48
49 class Configuration;
50 class TraceWriterObserver;
51
52 /**
53    Grabador de trazas
54    @see Logger
55 */
56 class TraceWriter : public Logger::Writer {
57 public:
58   static const int DefaultMaxKBSize = 4192 * 1024;
59
60   /**
61      Constructor.
62      \warning Si se usa este constructor las trazas se escribiran en un fichero del directorio temporal
63      con el mismo nombre que el pid del proceso.
64   */
65   TraceWriter();
66
67   /**
68      Constructor.
69      \param fileName Nombre del fichero de trazas.
70      \param maxSize Tama�o maximo del fichero de trazas expresando en bytes.
71   */
72   TraceWriter(const char* fileName, const int maxSize);
73
74   /**
75      Devuelve el tama�o maximo del fichero de trazas.
76      \return El tama�o maximo del fichero de trazas.
77   */
78   int getMaxSize() const throw() { return a_maxSize; }
79
80   /**
81      Metodo para cambiar dinamicamente la configuracion del grabador de trazas. Las seccciones
82      requeridas para el archivo de configuracion seran:
83
84      \code
85      [Trace]
86      MaxFileSize = Kbytes maximo de los ficheros de trazas. Por defecto sera 4096 Kbytes
87      Level = Nivel de trazas con el que comenzar la configuracion. Por defecto sera Debug para las
88      versiones con depuracion y Error para las versiones definitivas.
89      Clean = Un 1 indica que los ficheros de trazas usados hasta el momento deben borrarse y un 0
90      indica que deben mantenerse. Por defecto sera 1.
91      \endcode
92
93      Todos los parametros de la seccion \em Trace son opcionales.
94
95      \param fileName Nombre del fichero de trazas.
96      \param configuration Configuracion que contiene las variables y secciones necesarias
97      para establecer la configuracion desea del grabador de trazas.
98
99      \warning La configuracion debera estar correctamente cargada. Ver Configuration::load.
100   */
101   void setup(const char* fileName, const Configuration& configuration) throw();
102
103   /**
104      Metodo para cambiar dinamicamente la configuracion del grabador de trazas.
105
106      \param fileName Nombre del fichero de trazas.
107      \param maxSize Tama�o maximo del fichero de trazas expresando en bytes. Un valor 0 mantiene
108      el valor del tama�o estahlecido hasta el momento.
109      \param clean \em true Indica que los ficheros de trazas usados hasta el momento deben
110      borrase, \em false indica que los ficheros de trazas deben mantenerse.
111
112      \warning Solo deberia llamarse una vez para cambiar de la configuracion por defecto a la
113      configuracion particular de cada proceso.
114   */
115   void setup(const char* fileName, const int maxSize = 0, const bool clean = true) throw();
116
117   /**
118      Saca por pantalla la informacion relevente de este grabador de trazas.
119   */
120   void printResume() throw();
121
122   /**
123      Conecta esta instancia con un TraceWriterObserver, lo que permitira que esta instancia
124      conozca cuando se abre o cierra el fichero asociado a la escritura de trazas.
125
126      Este metodo puede invocarse tantas veces como sea necesario con distintas instancias de observador.
127
128      \param observer Instancia del observador que recibira las notificaciones de apertura y
129      cierre del fichero usado para sacar las trazas.
130
131      \warning La instancia del TraceWriterObserver debera estar disponible durante toda
132      la ejecucion.
133   */
134   void attach(TraceWriterObserver* observer) throw();
135
136 private:
137   typedef std::vector <TraceWriterObserver*>::iterator observer_iterator;
138
139   static const int ErrorStream = 2;
140
141   class GuardNoLog {
142   public:
143     GuardNoLog(NRMutex& mutex) : a_mutex(mutex) { mutex.lock(); }
144     ~GuardNoLog() { a_mutex.unlock(); }
145   private:
146     NRMutex& a_mutex;
147   };
148
149   std::string a_outputFile;
150   std::string a_outputOldFile;
151   int a_maxSize;
152   int a_stream;
153   Microsecond a_lastTime;
154   std::string a_date;
155   NRMutex a_mutex;
156   std::vector <TraceWriterObserver*> a_observers;
157   bool a_observed;
158
159   observer_iterator observer_begin() throw() { return a_observers.begin(); }
160   observer_iterator observer_end() throw() { return a_observers.end(); }
161
162   static TraceWriterObserver* observer(observer_iterator& ii) throw() { return *ii; }
163
164   void initialize(const char*) throw() { printResume(); }
165   void do_write(int level, const char* text, ...) throw();
166   const char* getDate() throw();
167   int prepareOutput(const char* date) throw();
168 };
169
170 }
171
172 #endif