logging.nim 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf, Dominik Picheta
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a simple logger.
  10. ##
  11. ## It has been designed to be as simple as possible to avoid bloat.
  12. ## If this library does not fulfill your needs, write your own.
  13. ##
  14. ## Basic usage
  15. ## ===========
  16. ##
  17. ## To get started, first create a logger:
  18. ##
  19. ## .. code-block::
  20. ## import logging
  21. ##
  22. ## var logger = newConsoleLogger()
  23. ##
  24. ## The logger that was created above logs to the console, but this module
  25. ## also provides loggers that log to files, such as the
  26. ## `FileLogger<#FileLogger>`_. Creating custom loggers is also possible by
  27. ## inheriting from the `Logger<#Logger>`_ type.
  28. ##
  29. ## Once a logger has been created, call its `log proc
  30. ## <#log.e,ConsoleLogger,Level,varargs[string,]>`_ to log a message:
  31. ##
  32. ## .. code-block::
  33. ## logger.log(lvlInfo, "a log message")
  34. ## # Output: INFO a log message
  35. ##
  36. ## The ``INFO`` within the output is the result of a format string being
  37. ## prepended to the message, and it will differ depending on the message's
  38. ## level. Format strings are `explained in more detail
  39. ## here<#basic-usage-format-strings>`_.
  40. ##
  41. ## There are six logging levels: debug, info, notice, warn, error, and fatal.
  42. ## They are described in more detail within the `Level enum's documentation
  43. ## <#Level>`_. A message is logged if its level is at or above both the logger's
  44. ## ``levelThreshold`` field and the global log filter. The latter can be changed
  45. ## with the `setLogFilter proc<#setLogFilter,Level>`_.
  46. ##
  47. ## **Warning:**
  48. ## * For loggers that log to a console or to files, only error and fatal
  49. ## messages will cause their output buffers to be flushed immediately.
  50. ## Use the `flushFile proc <io.html#flushFile,File>`_ to flush the buffer
  51. ## manually if needed.
  52. ##
  53. ## Handlers
  54. ## --------
  55. ##
  56. ## When using multiple loggers, calling the log proc for each logger can
  57. ## become repetitive. Instead of doing that, register each logger that will be
  58. ## used with the `addHandler proc<#addHandler,Logger>`_, which is demonstrated
  59. ## in the following example:
  60. ##
  61. ## .. code-block::
  62. ## import logging
  63. ##
  64. ## var consoleLog = newConsoleLogger()
  65. ## var fileLog = newFileLogger("errors.log", levelThreshold=lvlError)
  66. ## var rollingLog = newRollingFileLogger("rolling.log")
  67. ##
  68. ## addHandler(consoleLog)
  69. ## addHandler(fileLog)
  70. ## addHandler(rollingLog)
  71. ##
  72. ## After doing this, use either the `log template
  73. ## <#log.t,Level,varargs[string,]>`_ or one of the level-specific templates,
  74. ## such as the `error template<#error.t,varargs[string,]>`_, to log messages
  75. ## to all registered handlers at once.
  76. ##
  77. ## .. code-block::
  78. ## # This example uses the loggers created above
  79. ## log(lvlError, "an error occurred")
  80. ## error("an error occurred") # Equivalent to the above line
  81. ## info("something normal happened") # Will not be written to errors.log
  82. ##
  83. ## Note that a message's level is still checked against each handler's
  84. ## ``levelThreshold`` and the global log filter.
  85. ##
  86. ## Format strings
  87. ## --------------
  88. ##
  89. ## Log messages are prefixed with format strings. These strings contain
  90. ## placeholders for variables, such as ``$time``, that are replaced with their
  91. ## corresponding values, such as the current time, before they are prepended to
  92. ## a log message. Characters that are not part of variables are unaffected.
  93. ##
  94. ## The format string used by a logger can be specified by providing the `fmtStr`
  95. ## argument when creating the logger or by setting its `fmtStr` field afterward.
  96. ## If not specified, the `default format string<#defaultFmtStr>`_ is used.
  97. ##
  98. ## The following variables, which must be prefixed with a dollar sign (``$``),
  99. ## are available:
  100. ##
  101. ## ============ =======================
  102. ## Variable Output
  103. ## ============ =======================
  104. ## $date Current date
  105. ## $time Current time
  106. ## $datetime $dateT$time
  107. ## $app `os.getAppFilename()<os.html#getAppFilename>`_
  108. ## $appname Base name of ``$app``
  109. ## $appdir Directory name of ``$app``
  110. ## $levelid First letter of log level
  111. ## $levelname Log level name
  112. ## ============ =======================
  113. ##
  114. ## Note that ``$app``, ``$appname``, and ``$appdir`` are not supported when
  115. ## using the JavaScript backend.
  116. ##
  117. ## The following example illustrates how to use format strings:
  118. ##
  119. ## .. code-block::
  120. ## import logging
  121. ##
  122. ## var logger = newConsoleLogger(fmtStr="[$time] - $levelname: ")
  123. ## logger.log(lvlInfo, "this is a message")
  124. ## # Output: [19:50:13] - INFO: this is a message
  125. ##
  126. ## Notes when using multiple threads
  127. ## ---------------------------------
  128. ##
  129. ## There are a few details to keep in mind when using this module within
  130. ## multiple threads:
  131. ## * The global log filter is actually a thread-local variable, so it needs to
  132. ## be set in each thread that uses this module.
  133. ## * The list of registered handlers is also a thread-local variable. If a
  134. ## handler will be used in multiple threads, it needs to be registered in
  135. ## each of those threads.
  136. ##
  137. ## See also
  138. ## ========
  139. ## * `strutils module<strutils.html>`_ for common string functions
  140. ## * `strformat module<strformat.html>`_ for string interpolation and formatting
  141. ## * `strscans module<strscans.html>`_ for ``scanf`` and ``scanp`` macros, which
  142. ## offer easier substring extraction than regular expressions
  143. import strutils, times
  144. when not defined(js):
  145. import os
  146. type
  147. Level* = enum ## \
  148. ## Enumeration of logging levels.
  149. ##
  150. ## Debug messages represent the lowest logging level, and fatal error
  151. ## messages represent the highest logging level. ``lvlAll`` can be used
  152. ## to enable all messages, while ``lvlNone`` can be used to disable all
  153. ## messages.
  154. ##
  155. ## Typical usage for each logging level, from lowest to highest, is
  156. ## described below:
  157. ##
  158. ## * **Debug** - debugging information helpful only to developers
  159. ## * **Info** - anything associated with normal operation and without
  160. ## any particular importance
  161. ## * **Notice** - more important information that users should be
  162. ## notified about
  163. ## * **Warn** - impending problems that require some attention
  164. ## * **Error** - error conditions that the application can recover from
  165. ## * **Fatal** - fatal errors that prevent the application from continuing
  166. ##
  167. ## It is completely up to the application how to utilize each level.
  168. ##
  169. ## Individual loggers have a ``levelThreshold`` field that filters out
  170. ## any messages with a level lower than the threshold. There is also
  171. ## a global filter that applies to all log messages, and it can be changed
  172. ## using the `setLogFilter proc<#setLogFilter,Level>`_.
  173. lvlAll, ## All levels active
  174. lvlDebug, ## Debug level and above are active
  175. lvlInfo, ## Info level and above are active
  176. lvlNotice, ## Notice level and above are active
  177. lvlWarn, ## Warn level and above are active
  178. lvlError, ## Error level and above are active
  179. lvlFatal, ## Fatal level and above are active
  180. lvlNone ## No levels active; nothing is logged
  181. const
  182. LevelNames*: array[Level, string] = [
  183. "DEBUG", "DEBUG", "INFO", "NOTICE", "WARN", "ERROR", "FATAL", "NONE"
  184. ] ## Array of strings representing each logging level.
  185. defaultFmtStr* = "$levelname " ## The default format string.
  186. verboseFmtStr* = "$levelid, [$datetime] -- $appname: " ## \
  187. ## A more verbose format string.
  188. ##
  189. ## This string can be passed as the ``frmStr`` argument to procs that create
  190. ## new loggers, such as the `newConsoleLogger proc<#newConsoleLogger>`_.
  191. ##
  192. ## If a different format string is preferred, refer to the
  193. ## `documentation about format strings<#basic-usage-format-strings>`_
  194. ## for more information, including a list of available variables.
  195. type
  196. Logger* = ref object of RootObj
  197. ## The abstract base type of all loggers.
  198. ##
  199. ## Custom loggers should inherit from this type. They should also provide
  200. ## their own implementation of the
  201. ## `log method<#log.e,Logger,Level,varargs[string,]>`_.
  202. ##
  203. ## See also:
  204. ## * `ConsoleLogger<#ConsoleLogger>`_
  205. ## * `FileLogger<#FileLogger>`_
  206. ## * `RollingFileLogger<#RollingFileLogger>`_
  207. levelThreshold*: Level ## Only messages that are at or above this
  208. ## threshold will be logged
  209. fmtStr*: string ## Format string to prepend to each log message;
  210. ## defaultFmtStr is the default
  211. ConsoleLogger* = ref object of Logger
  212. ## A logger that writes log messages to the console.
  213. ##
  214. ## Create a new ``ConsoleLogger`` with the `newConsoleLogger proc
  215. ## <#newConsoleLogger>`_.
  216. ##
  217. ## See also:
  218. ## * `FileLogger<#FileLogger>`_
  219. ## * `RollingFileLogger<#RollingFileLogger>`_
  220. useStderr*: bool ## If true, writes to stderr; otherwise, writes to stdout
  221. when not defined(js):
  222. type
  223. FileLogger* = ref object of Logger
  224. ## A logger that writes log messages to a file.
  225. ##
  226. ## Create a new ``FileLogger`` with the `newFileLogger proc
  227. ## <#newFileLogger,File>`_.
  228. ##
  229. ## **Note:** This logger is not available for the JavaScript backend.
  230. ##
  231. ## See also:
  232. ## * `ConsoleLogger<#ConsoleLogger>`_
  233. ## * `RollingFileLogger<#RollingFileLogger>`_
  234. file*: File ## The wrapped file
  235. RollingFileLogger* = ref object of FileLogger
  236. ## A logger that writes log messages to a file while performing log
  237. ## rotation.
  238. ##
  239. ## Create a new ``RollingFileLogger`` with the `newRollingFileLogger proc
  240. ## <#newRollingFileLogger,FileMode,int,int>`_.
  241. ##
  242. ## **Note:** This logger is not available for the JavaScript backend.
  243. ##
  244. ## See also:
  245. ## * `ConsoleLogger<#ConsoleLogger>`_
  246. ## * `FileLogger<#FileLogger>`_
  247. maxLines: int # maximum number of lines
  248. curLine: int
  249. baseName: string # initial filename
  250. baseMode: FileMode # initial file mode
  251. logFiles: int # how many log files already created, e.g. basename.1, basename.2...
  252. bufSize: int # size of output buffer (-1: use system defaults, 0: unbuffered, >0: fixed buffer size)
  253. var
  254. level {.threadvar.}: Level ## global log filter
  255. handlers {.threadvar.}: seq[Logger] ## handlers with their own log levels
  256. proc substituteLog*(frmt: string, level: Level,
  257. args: varargs[string, `$`]): string =
  258. ## Formats a log message at the specified level with the given format string.
  259. ##
  260. ## The `format variables<#basic-usage-format-strings>`_ present within
  261. ## ``frmt`` will be replaced with the corresponding values before being
  262. ## prepended to ``args`` and returned.
  263. ##
  264. ## Unless you are implementing a custom logger, there is little need to call
  265. ## this directly. Use either a logger's log method or one of the logging
  266. ## templates.
  267. ##
  268. ## See also:
  269. ## * `log method<#log.e,ConsoleLogger,Level,varargs[string,]>`_
  270. ## for the ConsoleLogger
  271. ## * `log method<#log.e,FileLogger,Level,varargs[string,]>`_
  272. ## for the FileLogger
  273. ## * `log method<#log.e,RollingFileLogger,Level,varargs[string,]>`_
  274. ## for the RollingFileLogger
  275. ## * `log template<#log.t,Level,varargs[string,]>`_
  276. runnableExamples:
  277. doAssert substituteLog(defaultFmtStr, lvlInfo, "a message") == "INFO a message"
  278. doAssert substituteLog("$levelid - ", lvlError, "an error") == "E - an error"
  279. var msgLen = 0
  280. for arg in args:
  281. msgLen += arg.len
  282. result = newStringOfCap(frmt.len + msgLen + 20)
  283. var i = 0
  284. while i < frmt.len:
  285. if frmt[i] != '$':
  286. result.add(frmt[i])
  287. inc(i)
  288. else:
  289. inc(i)
  290. var v = ""
  291. let app = when defined(js): "" else: getAppFilename()
  292. while frmt[i] in IdentChars:
  293. v.add(toLowerAscii(frmt[i]))
  294. inc(i)
  295. case v
  296. of "date": result.add(getDateStr())
  297. of "time": result.add(getClockStr())
  298. of "datetime": result.add(getDateStr() & "T" & getClockStr())
  299. of "app": result.add(app)
  300. of "appdir":
  301. when not defined(js): result.add(app.splitFile.dir)
  302. of "appname":
  303. when not defined(js): result.add(app.splitFile.name)
  304. of "levelid": result.add(LevelNames[level][0])
  305. of "levelname": result.add(LevelNames[level])
  306. else: discard
  307. for arg in args:
  308. result.add(arg)
  309. method log*(logger: Logger, level: Level, args: varargs[string, `$`]) {.
  310. raises: [Exception], gcsafe,
  311. tags: [RootEffect], base.} =
  312. ## Override this method in custom loggers. The default implementation does
  313. ## nothing.
  314. ##
  315. ## See also:
  316. ## * `log method<#log.e,ConsoleLogger,Level,varargs[string,]>`_
  317. ## for the ConsoleLogger
  318. ## * `log method<#log.e,FileLogger,Level,varargs[string,]>`_
  319. ## for the FileLogger
  320. ## * `log method<#log.e,RollingFileLogger,Level,varargs[string,]>`_
  321. ## for the RollingFileLogger
  322. ## * `log template<#log.t,Level,varargs[string,]>`_
  323. discard
  324. method log*(logger: ConsoleLogger, level: Level, args: varargs[string, `$`]) =
  325. ## Logs to the console with the given `ConsoleLogger<#ConsoleLogger>`_ only.
  326. ##
  327. ## This method ignores the list of registered handlers.
  328. ##
  329. ## Whether the message is logged depends on both the ConsoleLogger's
  330. ## ``levelThreshold`` field and the global log filter set using the
  331. ## `setLogFilter proc<#setLogFilter,Level>`_.
  332. ##
  333. ## **Note:** Only error and fatal messages will cause the output buffer
  334. ## to be flushed immediately. Use the `flushFile proc
  335. ## <io.html#flushFile,File>`_ to flush the buffer manually if needed.
  336. ##
  337. ## See also:
  338. ## * `log method<#log.e,FileLogger,Level,varargs[string,]>`_
  339. ## for the FileLogger
  340. ## * `log method<#log.e,RollingFileLogger,Level,varargs[string,]>`_
  341. ## for the RollingFileLogger
  342. ## * `log template<#log.t,Level,varargs[string,]>`_
  343. ##
  344. ## **Examples:**
  345. ##
  346. ## .. code-block::
  347. ## var consoleLog = newConsoleLogger()
  348. ## consoleLog.log(lvlInfo, "this is a message")
  349. ## consoleLog.log(lvlError, "error code is: ", 404)
  350. if level >= logging.level and level >= logger.levelThreshold:
  351. let ln = substituteLog(logger.fmtStr, level, args)
  352. when defined(js):
  353. let cln: cstring = ln
  354. {.emit: "console.log(`cln`);".}
  355. else:
  356. try:
  357. var handle = stdout
  358. if logger.useStderr:
  359. handle = stderr
  360. writeLine(handle, ln)
  361. if level in {lvlError, lvlFatal}: flushFile(handle)
  362. except IOError:
  363. discard
  364. proc newConsoleLogger*(levelThreshold = lvlAll, fmtStr = defaultFmtStr,
  365. useStderr = false): ConsoleLogger =
  366. ## Creates a new `ConsoleLogger<#ConsoleLogger>`_.
  367. ##
  368. ## By default, log messages are written to ``stdout``. If ``useStderr`` is
  369. ## true, they are written to ``stderr`` instead.
  370. ##
  371. ## For the JavaScript backend, log messages are written to the console,
  372. ## and ``useStderr`` is ignored.
  373. ##
  374. ## See also:
  375. ## * `newFileLogger proc<#newFileLogger,File>`_ that uses a file handle
  376. ## * `newFileLogger proc<#newFileLogger,FileMode,int>`_
  377. ## that accepts a filename
  378. ## * `newRollingFileLogger proc<#newRollingFileLogger,FileMode,int,int>`_
  379. ##
  380. ## **Examples:**
  381. ##
  382. ## .. code-block::
  383. ## var normalLog = newConsoleLogger()
  384. ## var formatLog = newConsoleLogger(fmtStr=verboseFmtStr)
  385. ## var errorLog = newConsoleLogger(levelThreshold=lvlError, useStderr=true)
  386. new result
  387. result.fmtStr = fmtStr
  388. result.levelThreshold = levelThreshold
  389. result.useStderr = useStderr
  390. when not defined(js):
  391. method log*(logger: FileLogger, level: Level, args: varargs[string, `$`]) =
  392. ## Logs a message at the specified level using the given
  393. ## `FileLogger<#FileLogger>`_ only.
  394. ##
  395. ## This method ignores the list of registered handlers.
  396. ##
  397. ## Whether the message is logged depends on both the FileLogger's
  398. ## ``levelThreshold`` field and the global log filter set using the
  399. ## `setLogFilter proc<#setLogFilter,Level>`_.
  400. ##
  401. ## **Notes:**
  402. ## * Only error and fatal messages will cause the output buffer
  403. ## to be flushed immediately. Use the `flushFile proc
  404. ## <io.html#flushFile,File>`_ to flush the buffer manually if needed.
  405. ## * This method is not available for the JavaScript backend.
  406. ##
  407. ## See also:
  408. ## * `log method<#log.e,ConsoleLogger,Level,varargs[string,]>`_
  409. ## for the ConsoleLogger
  410. ## * `log method<#log.e,RollingFileLogger,Level,varargs[string,]>`_
  411. ## for the RollingFileLogger
  412. ## * `log template<#log.t,Level,varargs[string,]>`_
  413. ##
  414. ## **Examples:**
  415. ##
  416. ## .. code-block::
  417. ## var fileLog = newFileLogger("messages.log")
  418. ## fileLog.log(lvlInfo, "this is a message")
  419. ## fileLog.log(lvlError, "error code is: ", 404)
  420. if level >= logging.level and level >= logger.levelThreshold:
  421. writeLine(logger.file, substituteLog(logger.fmtStr, level, args))
  422. if level in {lvlError, lvlFatal}: flushFile(logger.file)
  423. proc defaultFilename*(): string =
  424. ## Returns the filename that is used by default when naming log files.
  425. ##
  426. ## **Note:** This proc is not available for the JavaScript backend.
  427. var (path, name, _) = splitFile(getAppFilename())
  428. result = changeFileExt(path / name, "log")
  429. proc newFileLogger*(file: File,
  430. levelThreshold = lvlAll,
  431. fmtStr = defaultFmtStr): FileLogger =
  432. ## Creates a new `FileLogger<#FileLogger>`_ that uses the given file handle.
  433. ##
  434. ## **Note:** This proc is not available for the JavaScript backend.
  435. ##
  436. ## See also:
  437. ## * `newConsoleLogger proc<#newConsoleLogger>`_
  438. ## * `newFileLogger proc<#newFileLogger,FileMode,int>`_
  439. ## that accepts a filename
  440. ## * `newRollingFileLogger proc<#newRollingFileLogger,FileMode,int,int>`_
  441. ##
  442. ## **Examples:**
  443. ##
  444. ## .. code-block::
  445. ## var messages = open("messages.log", fmWrite)
  446. ## var formatted = open("formatted.log", fmWrite)
  447. ## var errors = open("errors.log", fmWrite)
  448. ##
  449. ## var normalLog = newFileLogger(messages)
  450. ## var formatLog = newFileLogger(formatted, fmtStr=verboseFmtStr)
  451. ## var errorLog = newFileLogger(errors, levelThreshold=lvlError)
  452. new(result)
  453. result.file = file
  454. result.levelThreshold = levelThreshold
  455. result.fmtStr = fmtStr
  456. proc newFileLogger*(filename = defaultFilename(),
  457. mode: FileMode = fmAppend,
  458. levelThreshold = lvlAll,
  459. fmtStr = defaultFmtStr,
  460. bufSize: int = -1): FileLogger =
  461. ## Creates a new `FileLogger<#FileLogger>`_ that logs to a file with the
  462. ## given filename.
  463. ##
  464. ## ``bufSize`` controls the size of the output buffer that is used when
  465. ## writing to the log file. The following values can be provided:
  466. ## * ``-1`` - use system defaults
  467. ## * ``0`` - unbuffered
  468. ## * ``> 0`` - fixed buffer size
  469. ##
  470. ## **Note:** This proc is not available for the JavaScript backend.
  471. ##
  472. ## See also:
  473. ## * `newConsoleLogger proc<#newConsoleLogger>`_
  474. ## * `newFileLogger proc<#newFileLogger,File>`_ that uses a file handle
  475. ## * `newRollingFileLogger proc<#newRollingFileLogger,FileMode,int,int>`_
  476. ##
  477. ## **Examples:**
  478. ##
  479. ## .. code-block::
  480. ## var normalLog = newFileLogger("messages.log")
  481. ## var formatLog = newFileLogger("formatted.log", fmtStr=verboseFmtStr)
  482. ## var errorLog = newFileLogger("errors.log", levelThreshold=lvlError)
  483. let file = open(filename, mode, bufSize = bufSize)
  484. newFileLogger(file, levelThreshold, fmtStr)
  485. # ------
  486. proc countLogLines(logger: RollingFileLogger): int =
  487. result = 0
  488. let fp = open(logger.baseName, fmRead)
  489. for line in fp.lines():
  490. result.inc()
  491. fp.close()
  492. proc countFiles(filename: string): int =
  493. # Example: file.log.1
  494. result = 0
  495. var (dir, name, ext) = splitFile(filename)
  496. if dir == "":
  497. dir = "."
  498. for kind, path in walkDir(dir):
  499. if kind == pcFile:
  500. let llfn = name & ext & ExtSep
  501. if path.extractFilename.startsWith(llfn):
  502. let numS = path.extractFilename[llfn.len .. ^1]
  503. try:
  504. let num = parseInt(numS)
  505. if num > result:
  506. result = num
  507. except ValueError: discard
  508. proc newRollingFileLogger*(filename = defaultFilename(),
  509. mode: FileMode = fmReadWrite,
  510. levelThreshold = lvlAll,
  511. fmtStr = defaultFmtStr,
  512. maxLines = 1000,
  513. bufSize: int = -1): RollingFileLogger =
  514. ## Creates a new `RollingFileLogger<#RollingFileLogger>`_.
  515. ##
  516. ## Once the current log file being written to contains ``maxLines`` lines,
  517. ## a new log file will be created, and the old log file will be renamed.
  518. ##
  519. ## ``bufSize`` controls the size of the output buffer that is used when
  520. ## writing to the log file. The following values can be provided:
  521. ## * ``-1`` - use system defaults
  522. ## * ``0`` - unbuffered
  523. ## * ``> 0`` - fixed buffer size
  524. ##
  525. ## **Note:** This proc is not available in the JavaScript backend.
  526. ##
  527. ## See also:
  528. ## * `newConsoleLogger proc<#newConsoleLogger>`_
  529. ## * `newFileLogger proc<#newFileLogger,File>`_ that uses a file handle
  530. ## * `newFileLogger proc<#newFileLogger,FileMode,int>`_
  531. ## that accepts a filename
  532. ##
  533. ## **Examples:**
  534. ##
  535. ## .. code-block::
  536. ## var normalLog = newRollingFileLogger("messages.log")
  537. ## var formatLog = newRollingFileLogger("formatted.log", fmtStr=verboseFmtStr)
  538. ## var shortLog = newRollingFileLogger("short.log", maxLines=200)
  539. ## var errorLog = newRollingFileLogger("errors.log", levelThreshold=lvlError)
  540. new(result)
  541. result.levelThreshold = levelThreshold
  542. result.fmtStr = fmtStr
  543. result.maxLines = maxLines
  544. result.bufSize = bufSize
  545. result.file = open(filename, mode, bufSize = result.bufSize)
  546. result.curLine = 0
  547. result.baseName = filename
  548. result.baseMode = mode
  549. result.logFiles = countFiles(filename)
  550. if mode == fmAppend:
  551. # We need to get a line count because we will be appending to the file.
  552. result.curLine = countLogLines(result)
  553. proc rotate(logger: RollingFileLogger) =
  554. let (dir, name, ext) = splitFile(logger.baseName)
  555. for i in countdown(logger.logFiles, 0):
  556. let srcSuff = if i != 0: ExtSep & $i else: ""
  557. moveFile(dir / (name & ext & srcSuff),
  558. dir / (name & ext & ExtSep & $(i+1)))
  559. method log*(logger: RollingFileLogger, level: Level, args: varargs[string, `$`]) =
  560. ## Logs a message at the specified level using the given
  561. ## `RollingFileLogger<#RollingFileLogger>`_ only.
  562. ##
  563. ## This method ignores the list of registered handlers.
  564. ##
  565. ## Whether the message is logged depends on both the RollingFileLogger's
  566. ## ``levelThreshold`` field and the global log filter set using the
  567. ## `setLogFilter proc<#setLogFilter,Level>`_.
  568. ##
  569. ## **Notes:**
  570. ## * Only error and fatal messages will cause the output buffer
  571. ## to be flushed immediately. Use the `flushFile proc
  572. ## <io.html#flushFile,File>`_ to flush the buffer manually if needed.
  573. ## * This method is not available for the JavaScript backend.
  574. ##
  575. ## See also:
  576. ## * `log method<#log.e,ConsoleLogger,Level,varargs[string,]>`_
  577. ## for the ConsoleLogger
  578. ## * `log method<#log.e,FileLogger,Level,varargs[string,]>`_
  579. ## for the FileLogger
  580. ## * `log template<#log.t,Level,varargs[string,]>`_
  581. ##
  582. ## **Examples:**
  583. ##
  584. ## .. code-block::
  585. ## var rollingLog = newRollingFileLogger("messages.log")
  586. ## rollingLog.log(lvlInfo, "this is a message")
  587. ## rollingLog.log(lvlError, "error code is: ", 404)
  588. if level >= logging.level and level >= logger.levelThreshold:
  589. if logger.curLine >= logger.maxLines:
  590. logger.file.close()
  591. rotate(logger)
  592. logger.logFiles.inc
  593. logger.curLine = 0
  594. logger.file = open(logger.baseName, logger.baseMode,
  595. bufSize = logger.bufSize)
  596. writeLine(logger.file, substituteLog(logger.fmtStr, level, args))
  597. if level in {lvlError, lvlFatal}: flushFile(logger.file)
  598. logger.curLine.inc
  599. # --------
  600. proc logLoop(level: Level, args: varargs[string, `$`]) =
  601. for logger in items(handlers):
  602. if level >= logger.levelThreshold:
  603. log(logger, level, args)
  604. template log*(level: Level, args: varargs[string, `$`]) =
  605. ## Logs a message at the specified level to all registered handlers.
  606. ##
  607. ## Whether the message is logged depends on both the FileLogger's
  608. ## `levelThreshold` field and the global log filter set using the
  609. ## `setLogFilter proc<#setLogFilter,Level>`_.
  610. ##
  611. ## **Examples:**
  612. ##
  613. ## .. code-block::
  614. ## var logger = newConsoleLogger()
  615. ## addHandler(logger)
  616. ##
  617. ## log(lvlInfo, "This is an example.")
  618. ##
  619. ## See also:
  620. ## * `debug template<#debug.t,varargs[string,]>`_
  621. ## * `info template<#info.t,varargs[string,]>`_
  622. ## * `notice template<#notice.t,varargs[string,]>`_
  623. ## * `warn template<#warn.t,varargs[string,]>`_
  624. ## * `error template<#error.t,varargs[string,]>`_
  625. ## * `fatal template<#fatal.t,varargs[string,]>`_
  626. bind logLoop
  627. bind `%`
  628. bind logging.level
  629. if level >= logging.level:
  630. logLoop(level, args)
  631. template debug*(args: varargs[string, `$`]) =
  632. ## Logs a debug message to all registered handlers.
  633. ##
  634. ## Debug messages are typically useful to the application developer only,
  635. ## and they are usually disabled in release builds, although this template
  636. ## does not make that distinction.
  637. ##
  638. ## **Examples:**
  639. ##
  640. ## .. code-block::
  641. ## var logger = newConsoleLogger()
  642. ## addHandler(logger)
  643. ##
  644. ## debug("myProc called with arguments: foo, 5")
  645. ##
  646. ## See also:
  647. ## * `log template<#log.t,Level,varargs[string,]>`_
  648. ## * `info template<#info.t,varargs[string,]>`_
  649. ## * `notice template<#notice.t,varargs[string,]>`_
  650. log(lvlDebug, args)
  651. template info*(args: varargs[string, `$`]) =
  652. ## Logs an info message to all registered handlers.
  653. ##
  654. ## Info messages are typically generated during the normal operation
  655. ## of an application and are of no particular importance. It can be useful to
  656. ## aggregate these messages for later analysis.
  657. ##
  658. ## **Examples:**
  659. ##
  660. ## .. code-block::
  661. ## var logger = newConsoleLogger()
  662. ## addHandler(logger)
  663. ##
  664. ## info("Application started successfully.")
  665. ##
  666. ## See also:
  667. ## * `log template<#log.t,Level,varargs[string,]>`_
  668. ## * `debug template<#debug.t,varargs[string,]>`_
  669. ## * `notice template<#notice.t,varargs[string,]>`_
  670. log(lvlInfo, args)
  671. template notice*(args: varargs[string, `$`]) =
  672. ## Logs an notice to all registered handlers.
  673. ##
  674. ## Notices are semantically very similar to info messages, but they are meant
  675. ## to be messages that the user should be actively notified about, depending
  676. ## on the application.
  677. ##
  678. ## **Examples:**
  679. ##
  680. ## .. code-block::
  681. ## var logger = newConsoleLogger()
  682. ## addHandler(logger)
  683. ##
  684. ## notice("An important operation has completed.")
  685. ##
  686. ## See also:
  687. ## * `log template<#log.t,Level,varargs[string,]>`_
  688. ## * `debug template<#debug.t,varargs[string,]>`_
  689. ## * `info template<#info.t,varargs[string,]>`_
  690. log(lvlNotice, args)
  691. template warn*(args: varargs[string, `$`]) =
  692. ## Logs a warning message to all registered handlers.
  693. ##
  694. ## A warning is a non-error message that may indicate impending problems or
  695. ## degraded performance.
  696. ##
  697. ## **Examples:**
  698. ##
  699. ## .. code-block::
  700. ## var logger = newConsoleLogger()
  701. ## addHandler(logger)
  702. ##
  703. ## warn("The previous operation took too long to process.")
  704. ##
  705. ## See also:
  706. ## * `log template<#log.t,Level,varargs[string,]>`_
  707. ## * `error template<#error.t,varargs[string,]>`_
  708. ## * `fatal template<#fatal.t,varargs[string,]>`_
  709. log(lvlWarn, args)
  710. template error*(args: varargs[string, `$`]) =
  711. ## Logs an error message to all registered handlers.
  712. ##
  713. ## Error messages are for application-level error conditions, such as when
  714. ## some user input generated an exception. Typically, the application will
  715. ## continue to run, but with degraded functionality or loss of data, and
  716. ## these effects might be visible to users.
  717. ##
  718. ## **Examples:**
  719. ##
  720. ## .. code-block::
  721. ## var logger = newConsoleLogger()
  722. ## addHandler(logger)
  723. ##
  724. ## error("An exception occurred while processing the form.")
  725. ##
  726. ## See also:
  727. ## * `log template<#log.t,Level,varargs[string,]>`_
  728. ## * `warn template<#warn.t,varargs[string,]>`_
  729. ## * `fatal template<#fatal.t,varargs[string,]>`_
  730. log(lvlError, args)
  731. template fatal*(args: varargs[string, `$`]) =
  732. ## Logs a fatal error message to all registered handlers.
  733. ##
  734. ## Fatal error messages usually indicate that the application cannot continue
  735. ## to run and will exit due to a fatal condition. This template only logs the
  736. ## message, and it is the application's responsibility to exit properly.
  737. ##
  738. ## **Examples:**
  739. ##
  740. ## .. code-block::
  741. ## var logger = newConsoleLogger()
  742. ## addHandler(logger)
  743. ##
  744. ## fatal("Can't open database -- exiting.")
  745. ##
  746. ## See also:
  747. ## * `log template<#log.t,Level,varargs[string,]>`_
  748. ## * `warn template<#warn.t,varargs[string,]>`_
  749. ## * `error template<#error.t,varargs[string,]>`_
  750. log(lvlFatal, args)
  751. proc addHandler*(handler: Logger) =
  752. ## Adds a logger to the list of registered handlers.
  753. ##
  754. ## **Warning:** The list of handlers is a thread-local variable. If the given
  755. ## handler will be used in multiple threads, this proc should be called in
  756. ## each of those threads.
  757. ##
  758. ## See also:
  759. ## * `getHandlers proc<#getHandlers>`_
  760. runnableExamples:
  761. var logger = newConsoleLogger()
  762. addHandler(logger)
  763. doAssert logger in getHandlers()
  764. handlers.add(handler)
  765. proc getHandlers*(): seq[Logger] =
  766. ## Returns a list of all the registered handlers.
  767. ##
  768. ## See also:
  769. ## * `addHandler proc<#addHandler,Logger>`_
  770. return handlers
  771. proc setLogFilter*(lvl: Level) =
  772. ## Sets the global log filter.
  773. ##
  774. ## Messages below the provided level will not be logged regardless of an
  775. ## individual logger's ``levelThreshold``. By default, all messages are
  776. ## logged.
  777. ##
  778. ## **Warning:** The global log filter is a thread-local variable. If logging
  779. ## is being performed in multiple threads, this proc should be called in each
  780. ## thread unless it is intended that different threads should log at different
  781. ## logging levels.
  782. ##
  783. ## See also:
  784. ## * `getLogFilter proc<#getLogFilter>`_
  785. runnableExamples:
  786. setLogFilter(lvlError)
  787. doAssert getLogFilter() == lvlError
  788. level = lvl
  789. proc getLogFilter*(): Level =
  790. ## Gets the global log filter.
  791. ##
  792. ## See also:
  793. ## * `setLogFilter proc<#setLogFilter,Level>`_
  794. return level
  795. # --------------
  796. when not defined(testing) and isMainModule:
  797. var L = newConsoleLogger()
  798. when not defined(js):
  799. var fL = newFileLogger("test.log", fmtStr = verboseFmtStr)
  800. var rL = newRollingFileLogger("rolling.log", fmtStr = verboseFmtStr)
  801. addHandler(fL)
  802. addHandler(rL)
  803. addHandler(L)
  804. for i in 0 .. 25:
  805. info("hello", i)
  806. var nilString: string
  807. info "hello ", nilString