corpus

self-hosted listenbrainz and last.fm proxy
Log | Files | Refs | README | LICENSE

Log.purs (1684B)


      1 module Log
      2   ( info
      3   , warn
      4   , error
      5   ) where
      6 
      7 import Prelude
      8 
      9 import Data.DateTime (DateTime)
     10 import Data.Formatter.DateTime (FormatterCommand(..), format)
     11 import Data.List (fromFoldable)
     12 import Data.String (replaceAll, Pattern(..), Replacement(..))
     13 import Effect (Effect)
     14 import Effect.Class (class MonadEffect, liftEffect)
     15 import Effect.Console as Console
     16 import Effect.Now (nowDateTime)
     17 
     18 data LogLevel = DEBUG | INFO | WARN | ERROR
     19 
     20 instance showLogLevel :: Show LogLevel where
     21   show DEBUG = "DEBUG"
     22   show INFO = "INFO"
     23   show WARN = "WARN"
     24   show ERROR = "ERROR"
     25 
     26 formatTimestamp :: DateTime -> String
     27 formatTimestamp dt =
     28   format
     29     ( fromFoldable
     30         [ YearFull
     31         , Placeholder "-"
     32         , MonthTwoDigits
     33         , Placeholder "-"
     34         , DayOfMonthTwoDigits
     35         , Placeholder " "
     36         , Hours24
     37         , Placeholder ":"
     38         , MinutesTwoDigits
     39         , Placeholder ":"
     40         , SecondsTwoDigits
     41         , Placeholder "."
     42         , Milliseconds
     43         ]
     44     )
     45     dt
     46 
     47 logMessage :: LogLevel -> String -> Effect Unit
     48 logMessage level message = do
     49   now <- nowDateTime
     50   let ts = formatTimestamp now
     51   let
     52     sanitized = replaceAll (Pattern "\r\n") (Replacement " ") message
     53       # replaceAll (Pattern "\n") (Replacement " ")
     54       # replaceAll (Pattern "\r") (Replacement " ")
     55   Console.log $ "[" <> ts <> "] [" <> show level <> "] " <> sanitized
     56 
     57 info :: forall m. MonadEffect m => String -> m Unit
     58 info msg = liftEffect $ logMessage INFO msg
     59 
     60 warn :: forall m. MonadEffect m => String -> m Unit
     61 warn msg = liftEffect $ logMessage WARN msg
     62 
     63 error :: forall m. MonadEffect m => String -> m Unit
     64 error msg = liftEffect $ logMessage ERROR msg