Minimal code
Here is a minimal code (partly adopted from RLink), to get you started. First, load JLink:
Needs["JLink`"]
InstallJava[]
Here is the code:
ClearAll[logIt];
logIt[logger_,msg_String,mode_String]:=
Block[{trace, debug, info, warn, error, fatal},
With[{
method = mode /. {
"TRACE" -> trace,
"DEBUG" -> debug,
"INFO" -> info,
"WARN" -> warn,
"FATAL" -> fatal,
_ :> Return[$Failed, Block]
}},
JavaBlock@logger@method[JavaNew["java.lang.String", msg]]
]
];
logIt[logger_,msg_String]:=logIt[logger, msg, "INFO"];
And the initLogger
function:
ClearAll[initLogger];
initLogger[logger_, logFile_]:=
Module[{},
logger@removeAllAppenders[];
logger@addAppender[
JavaNew["org.apache.log4j.ConsoleAppender"]
];
logger@addAppender[
JavaNew[
"org.apache.log4j.FileAppender",
JavaNew["org.apache.log4j.SimpleLayout"],
logFile
]
];
logIt[logger, "Logger initialized"];
];
Example of use
Here is an example (I assume that log4j is already on the classpath, which is usually so, because it is used also internally in Mathematica):
LoadJavaClass["org.apache.log4j.Logger"]
Now create a logger instance:
logger = Logger`getLogger["MyApp"]
(* « JavaObject[org.apache.log4j.Logger]» *)
and the log file:
$logFile = FileNameJoin[{$TemporaryDirectory, "mylog.txt"}];
Now, initialize the logger:
initLogger[logger, $logFile]
You can test:
Import[$logFile, "String"]
(* "INFO - Logger initialized" *)
Now log something:
Do[
If[i < 5,
logIt[logger, "i = " <> ToString [i]],
logIt[logger, "fatal error", "FATAL"]; Break[]
],
{i, 1, 10}
]
check:
Import[$logFile, "String"]
"INFO - Logger initialized
INFO - i = 1
INFO - i = 2
INFO - i = 3
INFO - i = 4
FATAL - fatal error"
You can do more interesting things with loggers with log4j, but this example should get you started.
RLinkInit`rlogger
, and for which instead you can useLogger`getLogger["YourApp"]
. And you will have to firstLoadJavaClass["org.apache.log4j.Logger"]
, and add the log4j.jar to the classpath. $\endgroup$