gdritter repos new-inf-blog / master src / Inf / Log.hs
master

Tree @master (Download .tar.gz)

Log.hs @masterraw · history · blame

module Inf.Log
  ( debug
  , info
  , warn
  , error
  ) where

import           Control.Monad (when)
import qualified Data.Time as Time
import qualified System.IO.Unsafe as Unsafe
import qualified System.Posix.IO as Unix
import qualified System.Posix.Terminal as Unix
import           Prelude hiding (error)

isTTY :: Bool
isTTY = Unsafe.unsafePerformIO (Unix.queryTerminal (Unix.stdOutput))

timeFmt :: String
timeFmt = "[%Y-%m-%dT%H:%M:%S]"

timestamp :: IO String
timestamp = do
  now <- Time.getCurrentTime
  pure (Time.formatTime Time.defaultTimeLocale timeFmt now)

logMsg :: String -> [String] -> IO ()
logMsg color msg = do
  now <- timestamp
  when isTTY $ putStr color
  putStr (unwords (now:msg))
  when isTTY $ putStr "\x1b[39m"
  putStrLn ""

debug :: [String] -> IO ()
debug = logMsg "\x1b[97m"

info :: [String] -> IO ()
info = logMsg "\x1b[94m"

warn :: [String] -> IO ()
warn = logMsg "\x1b[93m"

error :: [String] -> IO ()
error = logMsg "\x1b[91m"