--- /dev/null
+module Logging (
+ init_logging,
+ log_debug,
+ log_error,
+ log_info,
+ log_warning )
+where
+
+import System.IO ( hPutStr, stderr, stdout )
+import System.Log ( LogRecord )
+import System.Log.Formatter ( LogFormatter )
+import System.Log.Logger (
+ Priority ( DEBUG, ERROR, INFO, WARNING ),
+ debugM,
+ errorM,
+ infoM,
+ rootLoggerName,
+ setHandlers,
+ setLevel,
+ updateGlobalLogger,
+ warningM )
+import System.Log.Handler.Simple (
+ GenericHandler(..),
+ streamHandler )
+
+import Terminal ( hPutBlueStr, hPutRedStr )
+
+log_debug :: String -> IO ()
+log_debug = debugM rootLoggerName
+
+log_error :: String -> IO ()
+log_error = errorM rootLoggerName
+
+log_info :: String -> IO ()
+log_info = infoM rootLoggerName
+
+log_warning :: String -> IO ()
+log_warning = warningM rootLoggerName
+
+-- | Debug messages output to the console don't get a prefix, since
+-- they're used to dump the network chatter.
+console_formatter :: LogRecord -> IO String
+console_formatter (DEBUG, msg) = return $ msg ++ "\n"
+console_formatter (prio, msg) = return $ (show prio) ++ ": " ++ msg ++ "\n"
+
+
+warn_formatter :: LogFormatter a
+warn_formatter _ x@(WARNING, _) _ = console_formatter x
+warn_formatter _ x@(ERROR, _) _ = console_formatter x
+warn_formatter _ _ _ = return ""
+
+info_formatter :: LogFormatter a
+info_formatter _ x@(INFO, _) _ = console_formatter x
+info_formatter _ _ _ = return ""
+
+debug_formatter :: LogFormatter a
+debug_formatter _ x@(DEBUG, _) _ = console_formatter x
+debug_formatter _ _ _ = return ""
+
+
+init_logging :: IO ()
+init_logging = do
+ -- Set the root logger to DEBUG level so that it will *attempt* to
+ -- process every message.
+ updateGlobalLogger rootLoggerName (setLevel DEBUG)
+
+ stdout_handler <- streamHandler stdout DEBUG
+ stderr_handler <- streamHandler stderr WARNING
+
+ let debug_handler = stdout_handler { formatter = debug_formatter,
+ writeFunc = hPutStr }
+
+ let info_handler = stdout_handler { formatter = info_formatter,
+ priority = INFO,
+ writeFunc = hPutBlueStr }
+
+ -- This also catches ERRORs.
+ let warn_handler = stderr_handler { formatter = warn_formatter,
+ priority = WARNING,
+ writeFunc = hPutRedStr }
+
+ -- Set debug, info, and warn handlers for the root log.
+ updateGlobalLogger
+ rootLoggerName
+ (setHandlers [debug_handler, info_handler, warn_handler])
stderr,
stdout )
import System.IO.Error (catchIOError)
+import System.Log.Logger ( getLogger, rootLoggerName, saveGlobalLogger )
import System.Timeout (timeout)
import CommandLine (get_args)
exit_no_feed_hosts,
exit_no_password,
exit_no_username )
+import Logging (
+ init_logging,
+ log_debug,
+ log_error,
+ log_info,
+ log_warning )
import qualified OptionalConfiguration as OC (
OptionalConfiguration(..),
from_rc )
-import Terminal (putGreenLn, report_error)
+import Terminal (putGreenLn)
import TSN.FeedHosts (FeedHosts(..))
import TSN.Xml (parse_xmlfid, xml_prologue)
--- | Receive a single line of text from a Handle, echoing it to stdout
--- in the process.
+-- | Receive a single line of text from a Handle, and send it to the
+-- debug log.
--
recv_line :: Handle -> IO String
recv_line h = do
line <- hGetLine h
- putStrLn line
+ log_debug line
return line
save_document cfg doc =
case maybe_path of
Nothing ->
- report_error "ERROR: document missing XML_File_ID element."
+ log_error "Document missing XML_File_ID element."
Just path -> do
already_exists <- doesFileExist path
when already_exists $ do
- let msg = "WARNING: file " ++ path ++ " already exists. Overwriting."
- report_error msg
+ let msg = "File " ++ path ++ " already exists, overwriting."
+ log_warning msg
writeFile path doc
+ log_info $ "Wrote file: " ++ path ++ "."
where
xmlfid = fmap show (parse_xmlfid doc)
filename = fmap (++ ".xml") xmlfid
prompt1 <- recv_prompt h
if prompt1 /= username_prompt then
- report_error "ERROR: didn't receive username prompt."
+ log_error "Didn't receive username prompt."
else do
send_line h (username cfg)
prompt2 <- recv_prompt h
if prompt2 /= password_prompt then
- report_error "ERROR: didn't receive password prompt."
+ log_error "Didn't receive password prompt."
else do
send_line h (password cfg)
_ <- recv_line h -- "The Sports Network"
connect_and_loop :: Configuration -> String -> IO ()
connect_and_loop cfg host = do
- putStrLn $ "Connecting to " ++ host ++ "..."
+ log_info $ "Connecting to " ++ host ++ "..."
bracket acquire_handle release_handle action
return ()
where
--
login_worked <- timeout five_seconds $ log_in cfg h
case login_worked of
- Nothing -> putStrLn "Login timed out (5s)."
+ Nothing -> log_info "Login timed out (5s)."
Just _ -> loop cfg h []
-- | The entry point of the program.
main :: IO ()
main = do
+ init_logging
+ root_logger <- getLogger rootLoggerName
+ saveGlobalLogger root_logger
+
rc_cfg <- OC.from_rc
cmd_cfg <- get_args
-- fall back on the default list (which gets merged from a
-- Configuration below).
when (null $ get_feed_hosts (OC.feed_hosts opt_config)) $ do
- report_error "ERROR: no feed hosts supplied."
+ log_error "No feed hosts supplied."
exitWith (ExitFailure exit_no_feed_hosts)
when (isNothing (OC.password opt_config)) $ do
- report_error "ERROR: no password supplied."
+ log_error "No password supplied."
exitWith (ExitFailure exit_no_password)
when (isNothing (OC.username opt_config)) $ do
- report_error "ERROR: no username supplied."
+ log_error "No username supplied."
exitWith (ExitFailure exit_no_username)
-- Finally, update a default config with any options that have been
round_robin cfg feed_host_idx = do
let hosts = get_feed_hosts $ feed_hosts cfg
let host = hosts !! feed_host_idx
- catchIOError (connect_and_loop cfg host) (report_error . show)
+ catchIOError (connect_and_loop cfg host) (log_error . show)
thread_sleep 10 -- Wait 10s before attempting to reconnect.
round_robin cfg $ (feed_host_idx + 1) `mod` (length hosts)
import System.FilePath ( (</>) )
import System.IO.Error (catchIOError)
-import Terminal (report_error)
+import Logging (log_error)
import TSN.FeedHosts (FeedHosts(..))
-- not serve much purpose. It could also be a security risk (visible
-- password) if the admin screws up.
home <- catchIOError getHomeDirectory (\e -> do
- report_error (show e)
+ log_error (show e)
return "$(HOME)")
let user_config_path = home </> ".htsnrc"
cfg <- DC.load [ DC.Optional user_config_path ]
module Terminal (
- putGreenLn,
- report_error)
+ hPutBlueStr,
+ hPutRedStr,
+ putGreenLn )
where
import Control.Monad.IO.Class (MonadIO(..))
ColorIntensity( Vivid ),
ConsoleLayer( Foreground ),
setSGR )
-import System.IO ( Handle, hPutStrLn, stderr )
+import System.IO ( Handle, hPutStr )
-- | Perform a computation (anything in MonadIO) with the given
-- graphics mode(s) enabled. Revert to the previous graphics mode
-- | Output the given line to the given handle, in red. The silly
-- camelCase name is for consistency with e.g. hPutStrLn.
-hPutRedLn :: Handle -> String -> IO ()
-hPutRedLn h = with_color Red . hPutStrLn h
+hPutRedStr :: Handle -> String -> IO ()
+hPutRedStr h = with_color Red . hPutStr h
--- | Output the given line to stdout. The silly camelCase name is for
--- consistency with e.g. putStrLn.
+-- | Output the given line to the given handle, in blue. The silly
+-- camelCase name is for consistency with e.g. hPutStrLn.
+hPutBlueStr :: Handle -> String -> IO ()
+hPutBlueStr h = with_color Blue . hPutStr h
+
+-- | Output the given line to stdout, in green. The silly camelCase
+-- name is for consistency with e.g. putStrLn.
putGreenLn :: String -> IO ()
putGreenLn = with_color Green . putStrLn
-
--- | Report an error (to stderr).
-report_error :: String -> IO ()
-report_error = hPutRedLn stderr