summaryrefslogtreecommitdiff
path: root/src/DPut.hs
blob: 6fd69040f6a182bff2a8895fcbc8aa1f689f5d67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module DPut where

import Control.Monad.IO.Class
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.IORef
import System.IO.Unsafe (unsafePerformIO)
import System.Log.Logger
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Debug.Trace

-- | Debug Tags, add more as needed, but ensure XAnnounce is always first, XMisc last
data DebugTag
  = XAnnounce
  | XBitTorrent
  | XDHT
  | XLan
  | XMan
  | XNetCrypto
  | XNetCryptoOut
  | XOnion
  | XRoutes
  | XPing
  | XRefresh
  | XJabber
  | XMisc
  | XNodeinfoSearch
  | XUnexpected -- Used only for special anomalous errors that we didn't expect to happen.
  | XUnused     -- Never commit code that uses XUnused.
  deriving (Eq, Ord, Show, Read, Enum, Bounded)

appName :: String
appName = "toxmpp"

(<.>) :: String -> String -> String
a <.> b = a ++ "." ++ b

dput :: MonadIO m => DebugTag -> String -> m ()
dput tag msg = liftIO $ debugM (appName <.> show tag) msg

dputB :: MonadIO m => DebugTag -> B.ByteString -> m ()
dputB tag msg = liftIO $ debugM (appName <.> show tag) (T.unpack . T.decodeUtf8 $ msg)

{-# NOINLINE verbosityMap #-}
verbosityMap :: IORef (Map.Map DebugTag Bool)
verbosityMap = unsafePerformIO $ newIORef (Map.empty)

-- | Trace version of 'dput' works in arbitrary monad, using unsafePerformIO.
tput :: Applicative m => DebugTag -> String -> m ()
tput tag msg =
  let mp = unsafePerformIO $ readIORef verbosityMap
    in if fromMaybe True (Map.lookup tag mp)
        then trace msg (pure ())
        else pure ()

-- | like 'trace' but parameterized with 'DebugTag'
dtrace :: DebugTag -> String -> a -> a
dtrace tag msg result = let mp = unsafePerformIO $ readIORef verbosityMap
                            in if fromMaybe True (Map.lookup tag mp)
                                then trace msg result
                                else result

setTagLevel :: Priority -> DebugTag -> IO ()
setTagLevel level tag = do
    updateGlobalLogger (appName <.> show tag) (setLevel level)
    modifyIORef verbosityMap (Map.insert tag (level <= DEBUG))

setQuiet :: DebugTag -> IO ()
setQuiet = setTagLevel WARNING

setVerbose :: DebugTag -> IO ()
setVerbose = setTagLevel DEBUG

getVerbose :: DebugTag -> IO Bool
getVerbose tag = do
    logger <- getLogger (appName <.> show tag)
    case getLevel logger of
        Just p | p <= DEBUG -> return True
        _ -> return False