Thursday, March 16, 2017

Example of Syntax Highlighting with Emacs

Recently I had a log file that was complex and reading it was tedious.  I wrote a quick syntax highlighting mode to make it easier on my bleary eyes.  Here's  an example using a hypothetical log file from a security robot that patrols a zoo at night.

Here's a snippet of the zoo log file we want to highlight, "2017-04-11a.zlog":

 ========== Zoo Application Started ==========
2017-03-15 09:55:34,329  INFO - Entering Primate zone
2017-03-15 09:58:38,553  INFO -   Gorillas - ok
2017-03-15 09:59:58,034  INFO -   Monkeys - ok
2017-03-15 09:58:38,553  INFO - Exiting Primate zone

2017-03-15 09:55:34,329  INFO - Entering Serengeti zone
2017-03-15 09:58:39,453  WARN -   Lions - not found in enclosure
2017-03-15 09:58:39,453  ERROR -  Lions - outside of cage!!
2017-03-15 09:58:38,553  INFO - Exiting Serengeti zone

We want to highlight the date/time and the type of entry "INFO,WARN,ERROR", whether we are entering or exiting and the type of animals.

The rules for highlighting are in the mode file, "zoo-log-mode.el":

;;example file of emacs syntax highlighting for log files - mitch fincher 2017
(setq zoo-log-highlights
    ("INFO\\|DEBUG\\|WARN\\|ERROR" . font-lock-function-name-face)
    ;; 2017-03-14 20:36:34,406
    ;; \\{4\\} is regex for repeat previous item 4 times
        ("[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [0-9][0-9]:[0-9][0-9]:[0-9][0-9],[0-9]\\{3\\}" . font-lock-constant-face)
    ("Entering\\|Exiting" . font-lock-keyword-face)
    ;;hightlight line that starts with "====" followed by anything
    ("^====.*" . font-lock-comment-face)
    ("Gorillas\\|Monkeys\\|Lions" . font-lock-doc-face)

(define-derived-mode zoo-log-mode fundamental-mode "zoo-log"
  "major mode for editing zoo-log log files."
  (setq font-lock-defaults '(zoo-log-highlights)))

;;override default colors for some
(set-face-foreground 'font-lock-doc-face        "Purple")
(set-face-foreground 'font-lock-comment-face        "LightGreen")

This is what it looks like in reverse video:

To get this to run quickly copy and paste the above file into your emacs directory.  Copy and paste the log file anyway on your system.

1. Load the "zoo-log-mode.el" file into a buffer and enter the command via M-x, "eval-buffer".
2. Load the zlog file into another buffer and enter the command "zoo-log-mode" to set the mode.
3. Notice you should have syntax highlighting.

To make this permanent, we need to hack your .emacs file.

1. Add this line at the top of you .emacs file:
(load "zoo-log-mode")
2.  In your auto-mode-alist, add the zoo mode.  This assumes the zoo log files have a ".zlog" extenstion:
(setq auto-mode-alist
      '(("\\.text$" . indented-text-mode)
        ("\\.zlog$" . zoo-log-mode) ;; this line

If you are wondering what faces are available, here they are:

Let me know if this works for you.

No comments: