hslogger-colorfmt-1.0.0: src/lib/System/Log/Color.hs
{-|
Module containing color definitions, mappings between @Priority@ and color,
and code to apply color to the terminal.
-}
module System.Log.Color
( ColorMap
, colorize
, black, red, green, yellow, blue, magenta, cyan, white
, grey, bred, bgreen , byellow, bblue, bmagenta, bcyan, bwhite
, colors16, colors256, noColor
)
where
import Data.List (find)
import Data.Word (Word8)
import System.Console.ANSI (ConsoleLayer (Foreground), SGR (..), setSGRCode)
import System.Log.Logger (Priority (..))
colorize :: ColorMap -> Priority -> String -> String
colorize colorMap prio str = case priorityColor of
(Just (swapColors, color)) ->
setSGRCode [SetPaletteColor Foreground color]
<> setSGRCode [SetSwapForegroundBackground swapColors]
<> str
<> setSGRCode [Reset]
Nothing -> str
where
priorityColor = snd <$> find ((== prio) . fst) colorMap
-- | These correspond to the basic 16 ANSI term color values
black, red, green, yellow, blue, magenta, cyan, white, grey, bred, bgreen,
byellow, bblue, bmagenta, bcyan, bwhite :: Word8
black = 0
red = 1
green = 2
yellow = 3
blue = 4
magenta = 5
cyan = 6
white = 7
grey = 8
bred = 9
bgreen = 10
byellow = 11
bblue = 12
bmagenta = 13
bcyan = 14
bwhite = 15
-- | This type maps a logging Priority to a pair indicating if the output
-- should be inverted (foreground and background swapped) and the color value
-- as a @Word8@ (an index into the 256 color palette)
type ColorMap = [(Priority, (Bool, Word8))]
-- | Use this @ColorMap@ to disable color entirely
noColor :: ColorMap
noColor = []
-- | Basic colors. Good when the term doesn't support 256.
colors16 :: ColorMap
colors16 =
[ (DEBUG , (False, bcyan))
, (INFO , (False, bgreen))
, (NOTICE , (False, bwhite))
, (WARNING , (False, byellow))
, (ERROR , (False, bred))
, (CRITICAL , (False, magenta))
, (ALERT , (False, bblue))
, (EMERGENCY, (True, bred))
]
-- | Some decent colors
colors256 :: ColorMap
colors256 =
[ (DEBUG , (False, 75)) -- Easier-to-read blue
, (INFO , (False, 156)) -- Minty green
, (NOTICE , (False, bwhite)) -- White
, (WARNING , (False, byellow)) -- Bright yellow
, (ERROR , (False, bred)) -- Bright red
, (CRITICAL , (False, 161)) -- Dull red
, (ALERT , (False, 206)) -- Brighter magenta
, (EMERGENCY, (True, bred)) -- Inverted bright red
]