Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (495)
Games in Android Showcase (114)
games submitted by our members
Games in WIP (563)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Logging the simple way  (Read 1843 times)
0 Members and 1 Guest are viewing this topic.
Offline Grunnt

JGO Wizard


Medals: 68
Projects: 8
Exp: 5 years


Complex != complicated


« Posted 2014-03-10 10:35:32 »

Here's a simple class I use in my LWJGL games to log info and exceptions. I also wrote a blog post about it explaining this class. Suggestions are welcome. Features:
- A simple, easy to maintain piece of code, no dependencies.
- Write info, warning, or error messages along with the exact time of occurrence.
- Write the full stack trace when an exception occurs.
- Logfile rotating: avoid filling op storage space by limiting maximum logfile size. A backup will be made of the current log when the size is reached, and this backup will be overwritten by the next backup.

Be sure to initialize at startup.

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  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Simple helper class for logging.
 */

public class Logging {

    static File file;
    static long maxSize;
    static SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

    /**
     * Initialize the log file.
     *
     * @param fileName
     * @param maxSize
     */

    public static void initialize(String fileName, long maxSizeKb) {
        if (file != null) {
            throw new RuntimeException("Logging already initialized");
        }
        file = new File(fileName);
        Logging.maxSize = maxSizeKb * 1024;
    }

    /**
     * Write error message to the logfile.
     *
     * @param message
     */

    public static void error(String message) {
        write("ERROR", message);
    }

    /**
     * Write error message to the logfile with additional exception information.
     *
     * @param message
     * @param t
     */

    public static void error(String message, Throwable t) {
        write("ERROR", message, t);
    }

    /**
     * Write warning message to the logfile.
     *
     * @param message
     */

    public static void warning(String message) {
        write("WARNING", message);
    }

    /**
     * Write information message to the logfile.
     *
     * @param message
     */

    public static void info(String message) {
        write("INFO", message);
    }

    private static void write(String prefix, String message) {
        checkRotate();
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) {
            bw.write("[" + prefix + " " + format.format(new Date()) + "] " + message + "\n");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    private static void write(String prefix, String message, Throwable t) {
        checkRotate();
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) {
            bw.write("[" + prefix + " " + format.format(new Date()) + "] " + message + ":\n");
            t.printStackTrace(new PrintWriter(bw));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        t.printStackTrace();
    }

    private static void checkRotate() {
        try {
            if (file.length() >= maxSize) {
                // Rotate logfiles
               File secondFile = new File(file.getName() + ".old");
                if (secondFile.exists()) {
                    secondFile.delete();
                }
                file.renameTo(secondFile);
            }
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
    }
}

Offline Dmap

Junior Newbie


Exp: 4 years



« Reply #1 - Posted 2014-04-03 09:21:25 »

If you want to you can add the full class name, method name and line number:

1  
2  
3  
4  
5  
6  
7  
String fullClassName = Thread.currentThread().getStackTrace()[3].getClassName();            
String className = fullClassName.substring(fullClassName.lastIndexOf(".") + 1);
String methodName = Thread.currentThread().getStackTrace()[3].getMethodName();
int lineNumber = Thread.currentThread().getStackTrace()[3].getLineNumber();

message = "at " + fullClassName + "." + methodName + "(" + className + ".java:" + lineNumber + ")"
           + " Msg: \"" + message + "\"";


In Eclipse you can double click the message and you go to the file/line (if you print it to logcat).
Offline Grunnt

JGO Wizard


Medals: 68
Projects: 8
Exp: 5 years


Complex != complicated


« Reply #2 - Posted 2014-04-03 09:29:06 »

Yeah that is a good one. You can also do this quite neatly using a PrintWriter, using the printStackTrace functionality:

1  
2  
3  
4  
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
exception.printStackTrace(printWriter);
String stackTrace = writer.toString();

Pages: [1]
  ignore  |  Print  
 
 

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Dwinin (28 views)
2014-09-12 09:08:26

Norakomi (57 views)
2014-09-10 13:57:51

TehJavaDev (75 views)
2014-09-10 06:39:09

Tekkerue (38 views)
2014-09-09 02:24:56

mitcheeb (57 views)
2014-09-08 06:06:29

BurntPizza (45 views)
2014-09-07 01:13:42

Longarmx (28 views)
2014-09-07 01:12:14

Longarmx (34 views)
2014-09-07 01:11:22

Longarmx (35 views)
2014-09-07 01:10:19

mitcheeb (40 views)
2014-09-04 23:08:59
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!