How to use Notepad++ to create a log file

The original Notepad of Microsoft Windows has a nice feature to create log files: Save a new file with the text .LOG as its first characters and a timestamp will be appended on subsequent openings.

Since my editor of choice nowadays is Notepad++ and I couldn’t find a similar solution for it (maybe I haven’t looked hard enough), I wrote one myself in the Python scripting language, with help of the plug-in PythonScript for Notepad++.

First, create two script files: Log.py and startup.py.

Put them both either into %ProgramFiles(x86)%\Notepad++\plugins\PythonScript\scripts or %APPDATA%\Notepad++\plugins\config\PythonScript\scripts, depending on your setup of Notepad++.

Also, change the NPPPythonScript initialisation mode (Notepad++ -> Plugins -> Python Script -> Configuration -> Initialisation) from LAZY to ATSTARTUP.

Log.py

That file contains the actual timestamp code and the notification callbacks, so that the script handles files that are opened when the text editor is already running.

Obviously, you can adjust the keyword and timestamp format to your own liking.

from Npp import *
import datetime

# To prevent that the same file gets be modified again while open, we'll keep an eye on all open .LOG files.
BufferIDList = set()

def updateLog (args):
	editor.gotoLine(0)

	if editor.getCurLine().startswith(".LOG"):
		bid = notepad.getCurrentBufferID()
		
		if bid not in BufferIDList:
			BufferIDList.add(bid)
			
			# Move to the end of the document and append timestamp etc.
			editor.gotoLine(editor.getLineCount())
			editor.appendText("\n\n-------------------\n\n")
			editor.appendText("%s\n\n" % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
			editor.gotoLine(editor.getLineCount())
			editor.scrollCaret()
		

def clearBufferIDList (args):
	try:
		BufferIDList.remove(args["bufferID"])
	except ValueError:
		pass

notepad.callback(clearBufferIDList, [NOTIFICATION.FILECLOSED])

# Tried FILEOPENED before, but had problems with it (wrong buffer getting updated, not updated at all or delayed...).
notepad.callback(updateLog, [NOTIFICATION.BUFFERACTIVATED])

startup.py

This will handle the case that a .LOG file starts the program in the first place, and should look like this:

from Log import updateLog
updateLog(0)

And that’s it!
(Tested with Notepad++ 6.4.3 (Unicode) and Python Script 0.9.2.0.)