1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
/** -*-C-*-ish
Kaya standard library
Copyright (C) 2004, 2005 Edwin Brady
This file is distributed under the terms of the GNU Lesser General
Public Licence. See COPYING for licence.
*/
module Logger;
import Prelude;
import IO;
import Time;
import Strings;
"Logging method.
LogFile is for sending logs directly to a file; it is less efficient because
it opens and closes a file on each log; use LogHandle for heavy logging.
LogString is for logging to a string in memory. The given string is modified
when it is logged to."
public data Logger
= LogFile(String fname)
| LogHandle(File handle)
| LogString(String log);
"Create a log file and return the log method.
The file will not actually be created until it is logged to."
public Logger makeLogFile(String fname)
{
return LogFile(fname);
}
"Create a log method from a file handle."
public Logger makeLogHandle(File handle)
{
return LogHandle(handle);
}
"Create a string logging method, initialised to the empty string."
public Logger makeLogString()
{
return LogString("");
}
"Finish logging.
This has no effect for files or strings, but closes the file handle."
public Void endLog(Logger l)
{
case l of {
LogFile(fn) -> ;
| LogString(s) -> ;
| LogHandle(f) -> close(f);
}
}
String leadzero(Int x) | x<10 = "0"+x
| default = String(x);
"Add to a log.
If timestamp is set, a timestamp is added to the log."
public Void log(var Logger l, String msg, Bool timestamp = true)
{
logmsg = msg +"\n";
if (timestamp) {
t = localtime();
stamp = "[" + substr(monthString(t.mon),0,3) + " " + t.mday + " " +
leadzero(t.hour) + ":" + leadzero(t.minute) + ":" +
leadzero(t.second) + "]";
logmsg = stamp + " " + logmsg;
}
case l of {
LogFile(fn) ->
f = open(fn,[Append]);
put(f,logmsg);
close(f);
| LogHandle(f) ->
put(f,logmsg);
| LogString(s) ->
l = LogString(s+logmsg);
}
}
"Log to many loggers at once.
Useful if you want the same log to go to several places, eg a log file and
standard output."
public Void logAll(var [Logger] ls, String msg, Bool timestamp = true)
{
for i in [0..size(ls)-1] {
log(ls[i],msg, timestamp);
}
}
|