[Resource] Error Logging to a file

Discussion in 'Resources' started by ThunderWaffeMC, Jan 27, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    ThunderWaffeMC

    Hi, there! Here's an easy to use resource that you can use to log errors to a .txt file so server owners and players can report or fix errors. Here's how to use it:

    Add the following to your main class and edit anything you want:

    Code:java
    1.  
    2. public void logError(String ID, String description, String cause, String solution) {
    3. try {
    4. File dataFolder = getDataFolder();
    5. if(!dataFolder.exists()) {
    6. dataFolder.mkdir();
    7. }
    8. File errorLog = new File(getDataFolder(), "errorlog.txt"); //edit 'errorlog.txt' to whatever
    9. if(!errorLog.exists()) {
    10. errorLog.createNewFile();
    11. getLogger().info("Created file '" + errorLog.getName() + "'."); //edit or remove if you don't want to log to console
    12. }
    13. FileWriter fileWriter = new FileWriter(errorLog, true);
    14. PrintWriter writer = new PrintWriter(fileWriter);
    15.  
    16. Calendar calender = Calendar.getInstance();
    17. calender.getTime();
    18.  
    19. SimpleDateFormat dateAndTimeFormat = new SimpleDateFormat("dd/MM/yyyy - h:mm a"); //edit to whatever date format you like
    20. String dateAndTime = dateAndTimeFormat.format(calender.getTime());
    21.  
    22. writer.println("[" + dateAndTime + "] Error #" + ID + " - " + description + " | Caused by: " + cause + " | Solution: " + solution + "."); //edit to whatever using the variables "dateAndTime", "ID", "description", "cause", "solution"
    23. writer.flush();
    24. writer.close();
    25.  
    26. getLogger().warning("An error was logged in the '" + dataFolder.getName() + "' folder."); //edit or remove if you don't want to log to console
    27. } catch (IOException exception) {
    28. exception.printStackTrace();
    29. }
    30. }
    31.  


    Now use the following to log the error to the file:

    Code:java
    1.  
    2. logError("someId", "Description of the error", "What caused the error", "A solution to fix the error");
    3.  


    Hope it helps!
     
Thread Status:
Not open for further replies.

Share This Page