Configuring Conditional Debug Logging in Elm with Runtime Flags
0 reputation · 28 Mar 2025, 21:42 UTC
0 reputation · 28 Mar 2025, 21:42 UTC
Design a helper around Elm's Debug.log that only emits messages when a runtime flag is enabled, allowing developers to retain useful alerts during development while suppressing noise in other contexts.
The Debug.log function is removed by the Elm optimizer in production builds, so any wrapper that assumes logging will always occur may give a false sense of visibility. The flag must be supplied via Elm flags (or a port) and kept in sync with the JavaScript initialization code; a mismatch can either produce excessive console output or silently suppress intended alerts. There is no official logging subsystem in the Elm Architecture, so teams must decide on a convention for severity levels, filtering, and port‑based integration.
32275 reputation · 29 Mar 2025, 03:03 UTC
Yes – you can create a small helper that forwards Debug.log only when a runtime Boolean flag is true, and the helper will be stripped entirely in optimized builds.
Debug.log calls are removed by the optimizer when you compile with elm make --optimize (or --release).debug : Bool.const app = Elm.Main.init({
node: document.getElementById('elm'),
flags: { debug: true } // set false for production
});
type alias Flags = { debug : Bool }
flagsDecoder : Json.Decode.Decoder Flags
flagsDecoder = Json.Decode.map2 Flags
(Json.Decode.field "debug" Json.Decode.bool)
DebugHelper.elm):
module DebugHelper exposing (debugLog)
debugLog : String -> a -> a
debugLog label value flags =
if flags.debug then
Debug.log label value
else
value
type alias Model = { debug : Bool, ... }
init : Flags -> ( Model, Cmd Msg )
init flags =
( { debug = flags.debug, ... } , Cmd.none )
Debug.log:
update msg model =
case msg of
SomeEvent ->
let
!_ = DebugHelper.debugLog "SomeEvent" someValue model.debug
in
( { model | ... } , Cmd.none )
_ -> ...
elm make --debug src/Main.elm – toggle the flag between true and false and observe console output.elm make --optimize src/Main.elm – run the compiled JavaScript; no Debug.log output should appear regardless of the flag.debug in JavaScript; the Elm runtime should fail to start with a decoding error.Are you compiling your production bundle with --optimize (or --release)? If not, the Debug.log calls will remain in the output and the wrapper will not suppress them.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.