Saturday, 15 December 2012

Java Simple Log Files

No matter what the program, you can be quite sure that logs are being written for whatever reason. It could be recording what a user is doing inside a website/database or recording character information in a game. In the case of a website or database it is important for companies to track potentially malicious activity, where they can see the time, person and even what action that person performed.

I wanted to do something simple where I write a username and the time the user is using the program to a text file. This example has no practical use alone but could perhaps be applied to a website/database later.

The code:
The code here probably needs a little explaining, particularly the matches statement. You should also be aware variable declarations and import statements have been excluded.

If we start from left to right, the caret "^" indicates the start of the line. The "(?i)" means we are ignoring letters case, next in the square brackets we're specifying that letters from a-z and numbers from 0-9 are valid in the String we're checking.

Just after the number check we're also allowing for underscores and hyphens. This is where the square brackets end and we're done specifying what is allowed in the String.

Finally in the curly brackets the numbers 3 and 15 are given separated by a comma. This means that the Strings length must be a minimum of 3 characters and a maximum of 15. Lastly the dollar sign indicates the end of line.

If you'd like to read more on the regular expression used, my source can be found here.

What we've just done is check for a standard format of usernames and if we find a valid username, then we exit the loop, otherwise the loop will repeat.

Moving on to writing the log:

We use try and catch because we're dealing with files and we don't want the program to crash.
You might be wondering why I use a BufferedWriter and FileWriter, this is because a BufferedWriter is more efficient at writing to files.
In my example the log file is simply being placed on the desktop. The "true" following the file path tells the program that if the file already exists, then we want to edit it and not delete the current contents.

Now the plan was to write the current date to the text file so in the following lines the date format is specified as "dd/MM/yyyy HH:mm".

You can read about what the letters mean here.

Now we got the date and we got the username, all that is left is writing to the file declared earlier in the program.
To write to the file using the BufferedWriter we call "bw.write()", where a String is given using some text and the 2 variables, after which a new line is written and we call "bw.close()" to say we're done editing the file.

The result in the file will look something like this:

Accessed by: Duane at: 15/12/2012 10:10

Thanks for your time and I hope you enjoyed it.

No comments:

Post a comment