Making a Log File for your Plugins

Discussion in 'Resources' started by gjossep, Jul 9, 2012.

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

    gjossep

    Making A Log File for Your Plugin!

    So i realize that lately there has been a lot of questions about making a log file for your plugin, here al show you how!

    So lets get started!

    The best idea for this is to make a method that writes to the log file and then call that method when you want to log something.

    So lets first make a method:
    Code:java
    1. public void logToFile()
    2. {
    3.  
    4. }


    Now what kind of parameters do we want?... We want a String, the string that will be logged to the file.

    So now our code looks like this:
    Code:java
    1. public void logToFile(String message)
    2. {
    3.  
    4. }


    Now we need to check if the Plugins DataFolder exists so we do:
    Code:java
    1. File dataFolder = getDataFolder();
    2. if(!dataFolder.exists())
    3. {
    4. dataFolder.mkdir();
    5. }

    This will check if it exists and if not it will make it!

    Now lets make a new file at the plugins data folder, We also need to check if the file exists and if it doesn't then we will make it.

    This is the code:

    Code:java
    1.  
    2. File saveTo = new File(getDataFolder(), "data.txt");
    3. if(!saveTo.exists())
    4. {
    5. try {
    6. saveTo.createNewFile();
    7. } catch (IOException e) {
    8. e.printStackTrace();
    9. }
    10. }
    11.  

    This will now make a file at your datafolder called data.txt, you can change the end part to what you want, like to .log, or .data. Just make sure you open it with a notepad or textedit.



    So now that we have the files all made and ready we need to put some info in it we do this with PrintWriter. So this is the code. Make sure if your using eclipse that you need to import everything!

    So here is the code for the PrintWriter:
    Code:java
    1. FileWriter fw = new FileWriter(saveTo, true);
    2. PrintWriter pw = new PrintWriter(fw);
    3.  

    Now that you have made a FileWriter with the file you made earlier. You can make a PrintWriter, you do that with adding the FileWriter to the PrintWriter, you see how the "fw" is a parameter of the PrintWriter, also make sure that the second parameter is true, so it will not overwrite what is already in the file!

    Now you can add these lines:
    Code:java
    1. pw.println(message);
    2. pw.flush();
    3. pw.close();


    This will add a line to the file and then close the line. Then you flush it out and close the stream.
    Thats all you need so now all together it should look like this:
    Code:java
    1. public void logToFile(String message)
    2.  
    3. {
    4.  
    5. try
    6. {
    7. File dataFolder = getDataFolder();
    8. if(!dataFolder.exists())
    9. {
    10. dataFolder.mkdir();
    11. }
    12.  
    13. File saveTo = new File(getDataFolder(), "data.txt");
    14. if (!saveTo.exists())
    15. {
    16. saveTo.createNewFile();
    17. }
    18.  
    19.  
    20. FileWriter fw = new FileWriter(saveTo, true);
    21.  
    22. PrintWriter pw = new PrintWriter(fw);
    23.  
    24. pw.println(message);
    25.  
    26. pw.flush();
    27.  
    28. pw.close();
    29.  
    30. } catch (IOException e)
    31. {
    32.  
    33. e.printStackTrace();
    34.  
    35. }
    36.  
    37. }


    Now you can do
    Code:java
    1. logToFile("Bob PLACED LAVA AT CORD:123213123");

    and your file will have it!

    Hope you like my tutorial, tell me where i can improve on, If you need anyhelp then PM me or do gjossep
    and all see it!
     
  2. Offline

    jacklin213

    thanks this helps alot
     
  3. Offline

    gjossep

    No problem!
     
  4. Offline

    McLuke500

    I already used this in my plugin PlayerLogger but didnt use flush and I'm no sure about close. Flushing closes the stream right? I never close the stream and with players coming and going its proberly got the stream open to 300 files or more. Would you recommend adding close and flush as what problems will it cause not doing so?
     
  5. Offline

    gjossep

    Well I just started reading some stuff more and found out that you don't need to do flush() because if you do close() it also performs a flush. And it's better to close your steam as its the same as cleaning out stuff that you don't need.

    Hope this helps
    Gjosse
     
  6. Offline

    xGhOsTkiLLeRx

    Here are my methods:

    Code:
    	// Log into the debug file
    	public static void logDebug(String string) {
    		if (debug) {
    			try {
    				PrintWriter writer = new PrintWriter(new FileWriter(debugFile, true), true);
    				if (string.equals("")) {
    					writer.write(System.getProperty("line.separator"));
    				}
    				else {
    					Date dt = new Date();
    					// Festlegung des Formats:
    					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    					String time = df.format(dt);
    					writer.write(time + " [ColorMe Debug] " + string);
    					writer.write(System.getProperty("line.separator"));
    				}
    				writer.close();
    			} catch (IOException e) {
    				Bukkit.getServer().getLogger().warning("[ColorMe] An error occurred while writing to the log! IOException");
    			}
    		}
    	}
    
    	// Check if debug is enabled and if a file needs to be created
    	private static void checkDebug() {
    		if (debug) {
    			debugFile = new File(Bukkit.getServer().getPluginManager().getPlugin("ColorMe").getDataFolder(), "debug.log");
    			if (!debugFile.exists()) {
    				try {
    					debugFile.createNewFile();
    				} catch (IOException e) {
    					Bukkit.getServer().getLogger().warning("[ColorMe] Failed to create the debug.log! IOException");
    				}
    			}
    		}
    	}
    (A complete server debug from start to end with 2 chat events would look like this: http://pastebin.com/YqvX4j2W )
    Feel free to use my code, too!
     
  7. Offline

    p000ison

  8. Offline

    jacklin213

    gjossep the "getDataFolder" doesnt work
     
  9. Offline

    gjossep

    Pm me your code and how your using it!
     
  10. Offline

    KeybordPiano459

    I want to use logToFile(string); in a file that isn't my main class, but it gives me errors. How do I do that? I would just put the code you provided in that other class, but getDataFolder() is part of JavaPlugin.
     
  11. Offline

    gjossep

    You don't need to use getDataFolder(), If you know where you want to save your file then you can do:
    Code:
    File test = new File("plugins/YOURPLUGINNAME/data.txt");
    And use that instead, then you won't get the problem.
    I hope that answers your question.
    Gjosse
     
  12. Offline

    Sagacious_Zed Bukkit Docs

    You should always use getDataFolder, plugins need not reside in the plugins folder, no matter how common place it may be.
     
    ferrybig likes this.
  13. The data folder should always exist (Don't have to check it)

    Couple things:
    • Cache the Writer's outside the method, so you don't have to create and close them every time
    • Call getLogger().info(message); (Better yet, find out what level to log it at)
    • You call getDataFolder to cache the value, and then call it again ignoring the cached value. Why?
     
  14. Offline

    KeybordPiano459

    Can't use that, Mac/Linux uses slashes for files, but windows uses backslash, so my plugin wouldn't work depending on the OS.
     
  15. Offline

    gjossep

    Ah sorry i forgot that, Im making Mac things now so i got used to this format..

    Thanks
     
  16. Offline

    KeybordPiano459

    Well then how would I fix this?
     
  17. Offline

    gjossep

    Depends, You could get the data folder and save it in a public variable in your main class, and then access it from the other class.

    Or you could make a enum with the data folder in it and then you have it.
     
  18. Offline

    Giant

    Don't worry about windows, whilst backslashes are preferred, it does accept normal slashes.

    gjossep use File.seperator instead of using a slash/backslash. File.seperator will pick the best option for the current system.

    tips48 the data folder that getDataFolder() returns does NOT always exist. This folder is dependent for your own plugin, and might have to be created before you can actually use it!
     
  19. Offline

    KeybordPiano459

    Are you sure? I'm pretty sure that windows only accepts backslashes.
     
  20. Offline

    Giant

    Considering that it kind of converts the path, yes. If you want to be save however, use File.separator.
     
  21. Offline

    jacklin213

    works fine when i create a config
    Code:
    File file = new File(getDataFolder() + File.separator + "config.yml");
     
  22. Offline

    Scullyking

    Great guide, how would I go about creating a file in a sub folder of the main plugin datafolder? :)
     
  23. Offline

    gjossep

    Almost the same: To make a other folder you can just do:
    Code:
    [CODE]File subFile = new File(getDataFolder(), "subFolder/File.txt");
    if(!subFolder.exists())
    {
    try {
    subFolder.mkdir(); *******Different Line
    } catch (IOException e) {
    e.printStackTrace();
    }
    }[/CODE]

    A folder is the same as a file. But to make it you use name.mkdir() instead of name.createNewFile().

    Then i hope you can guess how to make a file in that folder?

    If not:
    Code:
    File subFile = new File(getDataFolder(), "subFolder/File.txt");
    Thats just a hint.

    Thanks for the feedback.

    Need any help,
    Tag me.

    Gjosse
     
  24. Offline

    DarthVader3141

    Could you make a quick tutorial for reading (buffered) input line by line that works with the code here? Thanks.
     
  25. Offline

    Gabezter4

    gjossep how do I change the code to create the file when there is an error and it prints the error?
     
  26. Offline

    ThunderWaffeMC

    gjossep Is it possible to get text from the .txt file? For example; send a player a message with "some text here" if the .txt file looks like this:
    This is the log file: some text here
     
  27. Offline

    zack6849

    Just a tip for further optimization, don't create a new filewriter every time you want to log, lets say you use this for a logging plugin or something, you're creating a new filewriter lets say every second on an active server, its not much, and the garbage collector will get it, but its better to write code as if it the garbage collector sucks
     
  28. Offline

    metalhedd

    No logging levels, no timestamps... this is not a log file. it's just a text file that you write to very inefficiently. Anyone reading this would be better served by an actual logging module, there are 2 available to you from craftbukkit. log4j and java.util.logging.Logger
     
    Cirno and zack6849 like this.
  29. Offline

    macguy8

    metalhedd You do realize how old this is right?
     
  30. Offline

    Garris0n

    He's not the one who bumped it, and either way, it's resources, there's nothing wrong with bumping it to contribute further information.
     
    Jake6177 likes this.
Thread Status:
Not open for further replies.

Share This Page