Not that there aren't already a few ports of Log4J in Javascript as per this Wiki but the ones that I found have a low activity and no implementation is using browser's window.console
.
I found implementations with custom console windows, multiple color, rich capabilities to search through the logs ... pretty much what browsers are doing already nowdays through their own Console.
Because I wanted something very light and simple, I've created yet another port of Log4J in Javascript.
And because we live in modern times, I've chosen a modern language to do my job and that is: CoffeeScript
Log4JScript is licensed under Apache License 2.0.
var log = Log4J.Log.getLogger("myApp");
log.setLevel( Log4J.Level.TRACE );
log.addAppender( new Log4J.appender.ConsoleAppender( new Log4J.layout.MessageLayout() ) );
log.debug("Hello World !");
log.warn("Save the planet !");
log.error("Use an electric car.", new Error("don't use another car"));
There are 3 main components of Log4JScript, the same as the ones in Log4J: loggers
, appenders
, layouts
.
The Logger
class is the one which you'll be using to ... log the information, ofcourse.
Loggers can be assigned logging levels:
Log4J.Level.DEBUG
Log4J.Level.INFO
Log4J.Level.WARN
Log4J.Level.ERROR
Log4J.Level.FATAL
The Appender
is an output destination. Log4JScript implements 2 Appenders:
Log4J.appender.ConsoleAppender
- writing the ouput into Browser's Console. Basically it's callingwindow.console.log() / info() / debug() / warn()
Log4J.appender.AjaxAppender
- sending to a given endpoint a formData with the follosing properties:formatterLogMessage
,categoryName
,level
,message
,exception
.
The Layout
is responsible to create a log line from a given log message.
There are 2 layout classes implemented at the moment, and you can also add your own:
Log4J.layout.SimpleLayout
- writing lines likeDEBUG - Hello World!
Log4J.layout.MessageLayout
- writing only the message itselfHello World!
Using a Log4J implementation instead of window.console
has a few advantages:
- You can turn off some logs when you deploy in production with a single line of code:
log.setLevel( log.Level.WARN )
for instance. - You can log performance info and usage metrics of your application by using the
AjaxAppender
, saving this information on a server.
The build depends on Apache Maven.
For those familiar with maven
it's pretty straight forward:
mvn clean install
Build also integrates unit tests; in case the build fails b/c it cannot open a browser add browserPath
parameter:
mvn clean install -DbrowserPath=/path/to/my/browser
If you want to skip the tests, you can execute:
mvn clean install -Dmaven.test.skip=true