From 5b2e0b52bc6fbdbf47dc762ef74838d0cf95e403 Mon Sep 17 00:00:00 2001 From: mahlon Date: Fri, 23 Jun 2023 20:40:30 +0000 Subject: [PATCH] Suppose it would help to add the library file to the repo. FossilOrigin-Name: decf61cb072d0871085ee3dd111c1e2973fc6a0c7e73c76990185f1384cac3dc --- src/lib/logging.nim | 63 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/lib/logging.nim diff --git a/src/lib/logging.nim b/src/lib/logging.nim new file mode 100644 index 0000000..16b1564 --- /dev/null +++ b/src/lib/logging.nim @@ -0,0 +1,63 @@ +# vim: set et nosta sw=4 ts=4 : +# +# A global logger. Just write stuff to disk safely. +# + +############################################################# +# I M P O R T S +############################################################# + +import + std/os, + std/posix, + std/times + + +############################################################# +# T Y P E S +############################################################# + +type Logger = object + fh: File + + +############################################################# +# G L O B A L E X P O R T S +############################################################# + +var logger*: Logger + + +############################################################# +# M E T H O D S +############################################################# + +proc createLogger*( path: string ): void = + ## Get in line to open a write lock to the configured logfile at +path+. + ## This will block until it can get an exclusive lock. + let path = joinPath( getHomeDir(), path ) + logger = Logger() + logger.fh = path.open( fmAppend ) + + # Wait for exclusive lock. + discard logger.fh.getFileHandle.lockf( F_LOCK, 0 ) + logger.fh.writeLine "\n-------------------------------------------------------------------" + logger.fh.writeLine now().utc + + +proc close*( l: Logger ): void = + ## Release the lock and close/flush the file. + discard l.fh.getFileHandle.lockf( F_ULOCK, 0 ) + l.fh.close() + + +proc closed*( l: Logger ): bool = + ## Returns +false+ if the logfile has been opened. + return l.fh.isNil + + +proc log*( msg: string ): void = + ### Emit a line to the logfile. + if logger.closed: return + logger.fh.writeLine( msg ) +