source: tags/Mars-V0.9/mbase/MLog.cc

Last change on this file was 5820, checked in by tbretz, 20 years ago
*** empty log message ***
File size: 20.1 KB
Line 
1/* ======================================================================== *\
2!
3! *
4! * This file is part of MARS, the MAGIC Analysis and Reconstruction
5! * Software. It is distributed to you in the hope that it can be a useful
6! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
7! * It is distributed WITHOUT ANY WARRANTY.
8! *
9! * Permission to use, copy, modify and distribute this software and its
10! * documentation for any purpose is hereby granted without fee,
11! * provided that the above copyright notice appear in all copies and
12! * that both that copyright notice and this permission notice appear
13! * in supporting documentation. It is provided "as is" without express
14! * or implied warranty.
15! *
16!
17!
18! Author(s): Thomas Bretz, 12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
19!
20! Copyright: MAGIC Software Development, 2000-2005
21!
22!
23\* ======================================================================== */
24
25
26//////////////////////////////////////////////////////////////////////////////
27//
28// MLog
29//
30// This is what we call the logging-system.
31//
32// It is derived from the C++ streaming classes and can handle our
33// logging. The log output can be redirected to stdout, stderr, any other
34// stream or a root window.
35//
36// There is a global log-instance which you can use like cout, id is gLog.
37// A log-instance of your choice (gLog by default) is destributed to all
38// Task which are used in an eventloop, so that you can redirect the output
39// of one eventloop to where you want..
40//
41// The MLog stream has the advantage, that it can be used like the common
42// C++ streams (for example cout). It can redirect the stream to different
43// outputs (console, file, GUI) if necessary at the same time.
44//
45// It supports different debug levels. The debug level of the current
46// stream contents is set by SetDebugLevel, the output level of the
47// current stream can be set by SetOutputLevel.
48//
49// The header file MLogManip.h contains so called manipulators (like flush
50// or setw from iomanip.h) which can manipulate these levels from within
51// stream, for example:
52// gLog << debug(3) << "Hallo World " << endl;
53// sets the debug level of the following stream to 3
54//
55// edev(), ddev() can be used to enable/disable an output device from
56// within the stream. The enumerations are defined in MLog::_flags
57//
58// Commonly used abbreviations are also defined:
59// dbginf Prints source file name and line number. Used for output
60// which people may like to look up in the code
61// all Is streamed to the output in any case. Used for outputs
62// which are requested by the user (eg TObject::Print)
63// err Should be used for fatal errors which stops the current
64// processing, eg:
65// gLog << err << "ERROR: TObject::Copy - Stopped" << endl;
66// warn Warning means an error occured, but it is not clear whether
67// this results further procesing or not.
68// inf Informs the user about what's going on. Mostly usefull for
69// debugging, but in general not necessary at all.
70// dbg Use this for your private purpose to mark something as debug
71// output. This is _not_ ment to be persistent!
72//
73// If your console is capable of ANSI colors the stream is displayed
74// in several colors:
75// all: default
76// err: red
77// warn: yellow/brown
78// inf: green
79// dbg: blue (and all other levels)
80//
81// If you have a dark background on your console you might want to set
82// an environment variable, eg:
83// export MARSDEFINES=-DHAVE_DARKBACKGROUND
84// and recompile MLog.
85//
86// If your console can display it also 'underline' can be used. This
87// underlines a text till the next 'endl', eg:
88// gLog << underline << "This is important!" << endl;
89//
90// To switch off ANSI support call: SetNoColors()
91//
92// gLog is a global stream defined like cout or cerr
93//
94//////////////////////////////////////////////////////////////////////////////
95#include "MLog.h"
96
97#include <stdlib.h> // mkstemp
98
99#include <fstream>
100#include <iomanip>
101
102#include <TROOT.h> // gROOT->GetListOfCleanups()
103
104#ifdef _REENTRANT
105#include <TMutex.h>
106#endif
107#include <TGTextView.h>
108
109#include "MArgs.h"
110#include "MParContainer.h"
111
112#include "MLogHtml.h"
113
114ClassImp(MLog);
115
116using namespace std;
117
118#undef DEBUG
119//#define DEBUG
120
121
122// root 3.02:
123// check for TObjectWarning, TObject::Info, gErrorIgnoreLevel
124
125const char MLog::kESC = '\033'; // (char)27
126const char *const MLog::kEsc = "\033[";
127const char *const MLog::kReset = "\033[0m";
128const char *const MLog::kRed = "\033[31m";
129const char *const MLog::kGreen = "\033[32m";
130#ifdef HAVE_DARKBACKGROUND
131const char *const MLog::kYellow = "\033[33m\033[1m";
132#else
133const char *const MLog::kYellow = "\033[33m";
134#endif
135const char *const MLog::kBlue = "\033[34m";
136const char *const MLog::kUnderline = "\033[4m";;
137const char *const MLog::kBlink = "\033[5m";;
138const char *const MLog::kBright = "\033[1m";;
139const char *const MLog::kDark = "\033[2m";;
140
141//
142// This is the definition of the global log facility
143//
144MLog gLog;
145
146// --------------------------------------------------------------------------
147//
148// this strange usage of an unbufferd buffer is a workaround
149// to make it work on Alpha and Linux!
150//
151void MLog::Init()
152{
153
154 //
155 // Creat drawing semaphore
156 //
157#ifdef _REENTRANT
158 fMuxGui = new TMutex;
159 fMuxStream = new TMutex;
160#endif
161
162 fPlugins = new TList;
163 gROOT->GetListOfCleanups()->Add(fPlugins);
164 fPlugins->SetBit(kMustCleanup);
165
166 setp(&fBuffer, &fBuffer+1);
167 *this << '\0';
168}
169
170// --------------------------------------------------------------------------
171//
172// default constructor which initializes the streamer and sets the device
173// which is used for the output (i)
174//
175MLog::MLog(int i) : ostream(this), fPPtr(fBase), fEPtr(fBase+bsz), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(i), fIsNull(kFALSE), fOut(NULL), fOutAllocated(kFALSE), fGui(NULL), fNumLines(0)
176{
177 Init();
178}
179
180// --------------------------------------------------------------------------
181//
182// default constructor which initializes the streamer and sets the given
183// ofstream as the default output device
184//
185MLog::MLog(ofstream &out) : ostream(this), fPPtr(fBase), fEPtr(fBase+bsz), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(eFile), fIsNull(kFALSE), fOut(&out), fOutAllocated(kFALSE), fGui(NULL), fNumLines(0)
186{
187 Init();
188}
189
190// --------------------------------------------------------------------------
191//
192// default constructor which initializes the streamer and sets the given
193// TGTextView as the default output device
194//
195MLog::MLog(TGTextView &out) : ostream(this), fPPtr(fBase), fEPtr(fBase+bsz), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(eGui), fOut(NULL), fOutAllocated(kFALSE), fGui(&out), fNumLines(0)
196{
197 Init();
198}
199
200// --------------------------------------------------------------------------
201//
202// default constructor which initializes the streamer and opens a file with
203// the given name. Dependend on the flag the file is set as output device
204// or not.
205//
206MLog::MLog(const char *fname, int flag) : ostream(this), fPPtr(fBase), fEPtr(fBase+bsz), fOutputLevel(0), fDebugLevel((unsigned)-1), fDevice(eFile), fIsNull(kFALSE), fGui(NULL), fNumLines(0)
207{
208 Init();
209
210 AllocateFile(fname);
211 CheckFlag(eFile, flag);
212}
213
214// --------------------------------------------------------------------------
215//
216// Destructor, destroying the gui mutex.
217//
218MLog::~MLog()
219{
220 DeallocateFile();
221
222#ifdef DEBUG
223 TIter Next(fPlugins);
224 TObject *o=0;
225 while ((o=Next()))
226 {
227 cout << "Delete: " << o->GetName() << std::flush;
228 cout << " [" << o->ClassName() << "]" << endl;
229 delete o;
230 }
231
232 cout << "Delete: fPlugins " << fPlugins << "..." << std::flush;
233#endif
234
235 delete fPlugins;
236#ifdef DEBUG
237 cout << "done." << endl;
238#endif
239
240#ifdef _REENTRANT
241 delete fMuxStream;
242 delete fMuxGui;
243#endif
244}
245
246// --------------------------------------------------------------------------
247//
248// copyt constructor
249//
250/*
251MLog::MLog(MLog const& log)
252{
253// fOutputLevel = log.fOutputLevel;
254// fDebugLevel = log.fDebugLevel;
255// fDevice = log.fDevice;
256}
257*/
258
259void MLog::Underline()
260{
261 SetBit(kIsUnderlined);
262
263 fPlugins->ForEach(MLogPlugin, Underline)();
264
265 if (TestBit(eNoColors))
266 return;
267
268 if (fDevice&eStdout)
269 cout << kUnderline;
270
271 if (fDevice&eStderr)
272 cerr << kUnderline;
273}
274
275void MLog::Output(ostream &out, int len)
276{
277 if (!TestBit(eNoColors))
278 switch (fOutputLevel)
279 {
280 // do not output reset. Otherwise we reset underline in 0-mode
281 // case 1: out << MLog::kReset; break; // all
282 case 0: break; // all = background color
283 case 1: out << MLog::kRed; break; // err
284 case 2: out << MLog::kYellow; break; // warn
285 case 3: out << MLog::kGreen; break; // inf
286 default: out << MLog::kBlue; break; // all others (dbg)
287 }
288
289 if (len>0)
290 {
291 // Check for EOL
292 const Int_t endline = fBase[len-1]=='\n' ? 1 : 0;
293 // output text to screen (without trailing '\n')
294 out << TString(fBase, len-endline);
295 // reset colors if working with colors
296 if (!TestBit(eNoColors))
297 out << kReset;
298 // output EOL of check found EOL
299 if (endline)
300 {
301 out << '\n';
302 // Check whether text was underlined
303 if (TestBit(kIsUnderlined) && TestBit(eNoColors))
304 {
305 out << setw(len-1) << setfill('-') << "" << "\n";
306 ResetBit(kIsUnderlined);
307 }
308 }
309 }
310 out.flush();
311}
312
313void MLog::AddGuiLine(const TString &line)
314{
315 // add a new TString* to the array of gui lines
316 TString **newstr = new TString*[fNumLines+1];
317 memcpy(newstr, fGuiLines, fNumLines*sizeof(TString*));
318 if (fNumLines>0)
319 delete fGuiLines;
320 fGuiLines = newstr;
321
322 // add Gui line as last line of array
323 fGuiLines[fNumLines++] = new TString(line);
324}
325
326// --------------------------------------------------------------------------
327//
328// This is the function which writes the stream physically to a device.
329// If you want to add a new device this must be done here.
330//
331void MLog::WriteBuffer()
332{
333 //
334 // restart writing to the buffer at its first char
335 //
336 const int len = fPPtr - fBase;
337
338 fPPtr = fBase;
339
340 if (fIsNull)
341 return;
342
343 if (fDevice&eStdout)
344 Output(cout, len);
345
346 if (fDevice&eStderr)
347 Output(cerr, len);
348
349 if (fDevice&eFile && fOut)
350 fOut->write(fBase, len);
351
352 fPlugins->ForEach(MLogPlugin, SetColor)(fOutputLevel);
353 fPlugins->ForEach(MLogPlugin, WriteBuffer)(fBase, len);
354
355 if (fDevice&eGui && fGui)
356 {
357 // check whether the current text was flushed or endl'ed
358 const Int_t endline = fBase[len-1]=='\n' ? 1 : 0;
359
360 // for the gui remove trailing characters ('\n' or '\0')
361 fBase[len-endline]='\0';
362
363 // add new text to line storage
364 fGuiLine += fBase;
365
366 if (endline)
367 {
368 AddGuiLine(fGuiLine);
369 fGuiLine = "";
370
371 // Check whether text should be underlined
372 if (endline && TestBit(kIsUnderlined))
373 {
374 AddGuiLine("");
375 fGuiLines[fNumLines-1]->Append('-', fGuiLines[fNumLines-2]->Length());
376 ResetBit(kIsUnderlined);
377 }
378 }
379 }
380}
381
382void MLog::UpdateGui()
383{
384 if (fNumLines==0)
385 return;
386
387 // lock mutex
388 if (!LockUpdate("UpdateGui"))
389 {
390 Warning("UpdateGui", "Execution skipped");
391 return;
392 }
393
394 TGText &txt=*fGui->GetText();
395
396 // copy lines to TGListBox
397 for (int i=0; i<fNumLines; i++)
398 {
399 // Replace all tabs by 7 white spaces
400 fGuiLines[i]->ReplaceAll("\t", " ");
401 txt.InsText(TGLongPosition(0, txt.RowCount()), *fGuiLines[i]);
402 delete fGuiLines[i];
403 }
404 delete fGuiLines;
405
406 fNumLines=0;
407
408 // cut text box top 1000 lines
409 // while (txt.RowCount()>1000)
410 // txt.DelLine(1);
411
412 // show last entry
413 fGui->Layout();
414 fGui->SetVsbPosition(txt.RowCount()-1);
415
416 // tell a main loop, that list box contents have changed
417 fGui->SetBit(kHasChanged);
418
419 // release mutex
420 UnLockUpdate("UpdateGui");
421}
422
423bool MLog::LockUpdate(const char *msg)
424{
425#ifdef _REENTRANT
426 if (fMuxGui->Lock()==13)
427 {
428 Info("LockUpdate", "%s - mutex is already locked by this thread\n", msg);
429 return false;
430 }
431#endif
432 return true;
433}
434
435bool MLog::UnLockUpdate(const char *msg)
436{
437#ifdef _REENTRANT
438 if (fMuxGui->UnLock()==13)
439 {
440 Info("UnLockUpdate", "%s - tried to unlock mutex locked by other thread\n", msg);
441 return false;
442 }
443#endif
444 return true;
445}
446
447bool MLog::Lock(const char *msg)
448{
449#ifdef _REENTRANT
450 if (fMuxStream->Lock()==13)
451 {
452 Error("Lock", "%s - mutex is already locked by this thread\n", msg);
453 return false;
454 }
455// while (fMuxStream->Lock()==13)
456// usleep(1);
457// {
458// Error("Lock", "%s - mutex is already locked by this thread\n", msg);
459// return false;
460// }
461#endif
462 return true;
463}
464
465bool MLog::UnLock(const char *msg)
466{
467#ifdef _REENTRANT
468 if (fMuxStream->UnLock()==13)
469 {
470 Error("UnLock", "%s - tried to unlock mutex locked by other thread\n", msg);
471 return false;
472 }
473#endif
474 return true;
475}
476
477// --------------------------------------------------------------------------
478//
479// This is called to flush the buffer of the streaming devices
480//
481int MLog::sync()
482{
483 if (!LockUpdate("sync"))
484 usleep(1);
485 WriteBuffer();
486 UnLockUpdate("sync");
487
488 if (fDevice&eStdout)
489 {
490 if (!TestBit(eNoColors))
491 cout << kReset;
492 cout.flush();
493 }
494
495 if (fDevice&eStderr)
496 cerr.flush();
497
498 if (fDevice&eFile && fOut)
499 fOut->flush();
500
501 return 0;
502}
503
504// --------------------------------------------------------------------------
505//
506// This function comes from streambuf and should
507// output the buffer to the device (flush, endl)
508// or handle a buffer overflow (too many chars)
509// If a real overflow happens i contains the next
510// chars which doesn't fit into the buffer anymore.
511// If the buffer is not really filled i is EOF(-1).
512//
513int MLog::overflow(int i) // i=EOF means not a real overflow
514{
515 //
516 // no output if
517 //
518 if (fOutputLevel <= fDebugLevel)
519 {
520 if (!LockUpdate("overflow"))
521 usleep(1);
522
523 *fPPtr++ = (char)i;
524
525 if (fPPtr == fEPtr)
526 WriteBuffer();
527
528 UnLockUpdate("overflow");
529 }
530
531 return 0;
532}
533
534// --------------------------------------------------------------------------
535//
536// Print usage information setup in Setup()
537//
538void MLog::Usage()
539{
540 // 1 2 3 4 5 6 7 8
541 // 12345678901234567890123456789012345678901234567890123456789012345678901234567890
542 *this << " -v# Verbosity level # [default=2]" << endl;
543 *this << " -a, --no-colors Do not use Ansii color codes" << endl;
544 *this << " --log[=file] Write log-out to ascii-file [default: prgname.log]" << endl;
545 *this << " --html[=file] Write log-out to html-file [default: prgname.html]" << endl;
546 *this << " --debug[=n] Enable root debugging [default: gDebug=1]" << endl;
547 *this << " --null Null output (supresses all output)" << endl;
548}
549
550// --------------------------------------------------------------------------
551//
552// Setup MLog and global debug output from command line arguments.
553//
554void MLog::Setup(MArgs &arg)
555{
556 // FXIME: This is not really at a place where it belongs to!
557 gDebug = arg.HasOption("--debug=") ? arg.GetIntAndRemove("--debug=") : 0;
558 if (gDebug==0 && arg.HasOnlyAndRemove("--debug"))
559 gDebug=1;
560
561 TString f1 = arg.GetStringAndRemove("--log=", "");
562 if (f1.IsNull() && arg.HasOnlyAndRemove("--log"))
563 f1 = Form("%s.log", arg.GetName());
564 if (!f1.IsNull())
565 {
566 SetOutputFile(f1);
567 EnableOutputDevice(eFile);
568 }
569
570 TString f2 = arg.GetStringAndRemove("--html=", "");
571 if (f2.IsNull() && arg.HasOnlyAndRemove("--html"))
572 f2 = Form("%s.html", arg.GetName());
573 if (!f2.IsNull())
574 {
575 MLogHtml *html = new MLogHtml(f2);
576 html->SetBit(kCanDelete);
577 AddPlugin(html);
578 }
579
580 const Bool_t null = arg.HasOnlyAndRemove("--null");
581 if (null)
582 SetNullOutput();
583
584 if (arg.HasOnlyAndRemove("--no-colors") || arg.HasOnlyAndRemove("-a"))
585 SetNoColors();
586
587 SetDebugLevel(arg.GetIntAndRemove("-v", 2));
588}
589
590// --------------------------------------------------------------------------
591//
592// Read the setup from a TEnv:
593// MLog.VerbosityLevel: 0, 1, 2, 3, 4
594// MLog.DebugLevel: 0, 1, 2, 3, 4
595// MLog.NoColors
596//
597// Depending on your setup it might be correct to use something like:
598// Job1.MLog.VerbosityLevel: 1
599// Job1.DebugLevel: 2
600// Job1.MLog.NoColors
601//
602void MLog::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
603{
604 MParContainer mlog("MLog");
605
606 if (mlog.IsEnvDefined(env, prefix+"MLog", "VerbosityLevel", print))
607 SetDebugLevel(mlog.GetEnvValue(env, prefix+"MLog", "VerbosityLevel", 2));
608 else
609 if (mlog.IsEnvDefined(env, "MLog", "VerbosityLevel", print))
610 SetDebugLevel(mlog.GetEnvValue(env, "MLog", "VerbosityLevel", 2));
611
612 if (mlog.IsEnvDefined(env, prefix+"MLog", "DebugLevel", print))
613 gDebug = mlog.GetEnvValue(env, prefix+"MLog", "DebugLevel", 0);
614 else
615 if (mlog.IsEnvDefined(env, "MLog", "DebugLevel", print))
616 gDebug = mlog.GetEnvValue(env, "MLog", "DebugLevel", 0);
617
618 if (mlog.IsEnvDefined(env, prefix+"MLog", "NoColors", print))
619 SetNoColors(mlog.GetEnvValue(env, prefix+"MLog", "NoColors", kFALSE));
620 else
621 if (mlog.IsEnvDefined(env, "MLog", "NoColors", print))
622 SetNoColors(mlog.GetEnvValue(env, "MLog", "NoColors", kFALSE));
623}
624
625// --------------------------------------------------------------------------
626//
627// Read the setup from a TEnv:
628// MLog.VerbosityLevel: 0, 1, 2, 3, 4
629// MLog.DebugLevel: 0, 1, 2, 3, 4
630// MLog.NoColors
631//
632// Depending on your setup it might be correct to use something like:
633// Job1.MLog.VerbosityLevel: 1
634// Job1.DebugLevel: 2
635// Job1.MLog.NoColors
636//
637void MLog::WriteEnv(TEnv &env, TString prefix, Bool_t print) const
638{
639 if (!prefix.IsNull())
640 prefix += ".";
641 prefix += "MLog";
642
643 cout << "MLog::WriteEnv: not yet implemented!" << endl;
644}
645
646// --------------------------------------------------------------------------
647//
648// Create a new instance of an file output stream
649// an set the corresponding flag
650//
651void MLog::AllocateFile(const char *fname)
652{
653 // gcc 3.2:
654 char *txt = (char*)"logXXXXXX";
655
656 TString n(fname ? fname : txt);
657 gSystem->ExpandPathName(n);
658 fOut = new ofstream(n.Data());
659 fOutAllocated = kTRUE;
660}
661
662// --------------------------------------------------------------------------
663//
664// if fout was allocated by this instance of MLooging
665// delete it.
666//
667void MLog::DeallocateFile()
668{
669 if (fOutAllocated)
670 delete fOut;
671}
672
673// --------------------------------------------------------------------------
674//
675// if necessary delete the old in stance of the file
676// output stream and create a new one
677//
678void MLog::ReallocateFile(const char *fname)
679{
680 DeallocateFile();
681 AllocateFile(fname);
682}
683
684// --------------------------------------------------------------------------
685//
686// This function checks if a device should get enabled or disabled.
687//
688void MLog::CheckFlag(Flags_t chk, int flag)
689{
690 if (flag==-1)
691 return;
692
693 flag ? EnableOutputDevice(chk) : DisableOutputDevice(chk);
694}
695
696// --------------------------------------------------------------------------
697//
698// Add a plugin to which the output should be redirected, eg. MLogHtml
699// The user has to take care of its deletion. If the plugin is deleted
700// (and the kMustCleanup bit was not reset accidentaly) the plugin
701// is automatically removed from the list of active plugins.
702//
703// If MLog should take the ownership call plug->SetBit(kCanDelete);
704//
705void MLog::AddPlugin(MLogPlugin *plug)
706{
707 fPlugins->Add(plug);
708
709 // Make sure that it is recursively deleted from all objects in ListOfCleanups
710 plug->SetBit(kMustCleanup);
711}
Note: See TracBrowser for help on using the repository browser.