Switches and Logging

MonoMod's libraries have no configuration file. Their behavior is tuned through switches: named values that can come from environment variables, from .NET AppContext switches, or from code. This page explains where switch values come from and in which order, how values are parsed (including a surprising hexadecimal rule), every switch the libraries read, and how to use MonoMod's logger. Settings for the command-line tools are separate and documented on the Patcher, HookGen and DebugIL pages.

Where Switch Values Come From

Switches are managed by the static class MonoMod.Switches (in MonoMod.Utils). When MonoMod looks up a switch named X, it checks, in order:

  1. MonoMod's own dictionary. It is filled once, when the Switches class initializes, from every environment variable whose name starts with MONOMOD_ (case-sensitive): MONOMOD_X becomes switch X. Code can change it at runtime with Switches.SetSwitchValue("X", value).
  2. AppContext data named MonoMod.X (AppContext.GetData, or AppDomain.CurrentDomain.GetData where AppContext is unusable).
  3. AppContext switches named MonoMod.X (AppContext.TryGetSwitch).

Switches.ClearSwitchValue("X") removes an entry from MonoMod's dictionary so that lookups fall through to AppContext.

API Description
Switches.SetSwitchValue(string @switch, object? value) Sets a value in MonoMod's dictionary.
Switches.ClearSwitchValue(string @switch) Removes it.
Switches.TryGetSwitchValue(string @switch, out object? value) Raw lookup (dictionary, then AppContext data, then AppContext switch).
Switches.TryGetSwitchEnabled(string @switch, out bool isEnabled) Boolean lookup (dictionary, then AppContext switch, then AppContext data).
Constants Switches.RunningOnWine, Switches.DMDType, ... The switch names below.

Setting through AppContext in a project file, for runtimes that support it:

<ItemGroup>
  <RuntimeHostConfigurationOption Include="MonoMod.LogToFile" Value="monomod.log" />
</ItemGroup>

Warning: Switch names are case-sensitive. The environment variable must be spelled MONOMOD_LogToFile, not MONOMOD_LOGTOFILE: the part after the prefix becomes the switch name verbatim and is compared ordinally with LogToFile.

Warning: Many switches are read only once, very early. All logging switches are read when the logger is created, which happens before user code can call into MonoMod; RunningOnWine is read during the first OS detection. Calling SetSwitchValue later has no effect on those. Set them through environment variables or AppContext instead.

Value Parsing

Environment variable values are converted on a best-effort basis (BestEffortParseEnvVar in Switches.cs):

  1. An empty value becomes null.
  2. MonoMod tries to parse the value as a hexadecimal int, then a hexadecimal long.
  3. Then as a decimal int, then a decimal long.
  4. Then, if it starts with t, f, y or n (any case), as a boolean: true/false (via bool.TryParse), yes/y, no/n.
  5. Otherwise, the string is kept.

Boolean switches also accept numbers: non-zero is true, zero is false.

Warning: Because hexadecimal is tried first, numeric environment values are read as hex. MONOMOD_LogReplayQueueLength=100 gives a queue of 256 entries (0x100), and 10 means 16. Values made only of hex digits, such as cafe, become numbers too, so a string switch set to such a value is ignored (string switches are read with as string). Single digits 0–9 are unaffected.

Values set from code or AppContext are used as given. For boolean switches, a bool, int or long works, and a string works if bool.TryParse accepts it; another string (such as "yes") falls through to IConvertible.ToBoolean, which throws FormatException for strings.

Switch Reference

Platform and CLR Switches

RunningOnWine

Property Value
Type boolean
Read once, during the first OS detection
Default auto-detect

Forces PlatformDetection to report OSKind.Wine (true) or plain Windows (false) when it detects Windows. See How Wine is detected.

DebugClr

Property Value
Type boolean
Default false (assume a Release CLR)

Tells MonoMod.Core that it runs on a Debug or Checked build of CoreCLR. Some internal CLR data structures that MonoMod reads have a different layout in those builds, and the build flavor cannot be detected.

JitPath

Property Value
Type string (full path)
Default first loaded module whose extensionless name ends with clrjit

MonoMod.Core hooks the CoreCLR JIT to follow method recompilations, so it must find the JIT binary. When several CLRs are loaded in one process (for example .NET Framework 4.8 and .NET Core together), it can pick the wrong one. Set the full path of the real JIT here, during or shortly after CLR initialization and before MonoMod initializes. The path must still meet the naming criterion: otherwise a warning is printed and the value is ignored; if the path is not loaded, the default behavior is used.

HelperDropPath

Property Value
Type string (directory)
Default /tmp

On Unix systems MonoMod.Core writes a native helper binary to disk and loads it (to handle exceptions passing through its JIT hook, and on Apple M-series to patch JIT-executable memory). Use this switch when your system forbids loading executables from /tmp.

DynamicMethodDefinition Switches

These are read every time they are needed: DMDDebug when a DynamicMethodDefinition is constructed, DMDType and DMDDumpTo when it is generated.

DMDType

Property Value
Type string
Values dynamicmethod/dm, cecil/md, methodbuilder/mb (case-insensitive), or the full name of a DMDGenerator<TSelf> subclass
Default automatic selection

Forces a backend for DynamicMethodDefinition.Generate(). methodbuilder only works in the builds that include that backend (.NET Framework and net9.0+).

DMDDebug

Property Value
Type boolean
Default false

Default value of DynamicMethodDefinition.Debug: emit debug information where supported, and prefer MethodBuilder (in builds that have it) or otherwise Cecil. The repository's docs/Switches.md notes that a DMD with fault or filter blocks still uses MethodBuilder when Debug is set, even though that backend does not support them on .NET Framework.

DMDDumpTo

Property Value
Type string (directory)
Default unset (no dumps)

Writes generated DMD assemblies to this directory. Only the Cecil and MethodBuilder backends dump; combine with DMDDebug. Assembly names end with the backend's name.

Logging Switches

All of these are read once, when the logger is created.

Switch Type Effect
LogToFile string Enables a sink that writes every message to this file (created/truncated, UTF-8, auto-flushed). The value - writes to standard output.
LogToFileFilter string Comma- or semicolon-separated list of sources (case-insensitive) the file sink should keep, for example MonoMod.Core;MonoMod.RuntimeDetour. Empty or unset keeps all sources. A value that the env-var parser turns into a number (for example a single hex-looking word) is ignored, which also keeps all sources.
LogSpam boolean Includes Spam-level messages in the default (file and memory) sinks.
LogInMemory boolean Keeps messages in an in-memory buffer that a native debugger can read. The repository has a WinDbg script for it, tools/windbg-memlog.js (which, per docs/Debugging.md, assumes a 64-bit process).
LogRecordHoles boolean Always captures the values of interpolation "holes" in messages (mainly useful with the replay queue).
LogReplayQueueLength integer When non-zero, keeps this many recent messages and replays them to every new subscriber. Remember the hex parsing rule.

Logging

MonoMod logs through MonoMod.Logs.DebugLog. Each message has a source (the MonoMod assembly name, such as MonoMod.Utils, MonoMod.Core, MonoMod.RuntimeDetour), a time, and a level:

LogLevel Typical content
Spam Very detailed internals. Excluded by default.
Trace Step-by-step actions, such as Creating Hook from ... to ..., Applying Hook ....
Info Notable facts, such as Platform info: Windows x86_64.
Warning Recoverable problems, for example detour ordering conflicts.
Error Errors, for example an invalid DMDType.
Assert Failed internal assertions.

The default level filter (LogLevelFilter.DefaultFilter) is every level except Spam.

Writing the Log to a File or the Console

# Linux/macOS
MONOMOD_LogToFile=monomod.log ./MyGame
MONOMOD_LogToFile=- MONOMOD_LogToFileFilter=MonoMod.RuntimeDetour dotnet run
# Windows PowerShell
$env:MONOMOD_LogToFile = "monomod.log"
.\MyGame.exe

The file sink writes one line per message in the format [source](local time) Level: message, for example (illustrative):

[MonoMod.Utils](11/20/2026 10:15:02 AM) Info: Platform info: Windows x86_64
[MonoMod.RuntimeDetour](11/20/2026 10:15:02 AM) Trace: Creating Hook from Int32 TakeDamage(Int32) to ...

If the file cannot be opened, the logger records an error (Exception while trying to initialize writing logs to a file: ...) and continues without the sink.

Subscribing From Code

API Description
DebugLog.OnLog Static event of type OnLogMessage(string source, DateTime time, LogLevel level, string message), using the default level filter.
DebugLog.Subscribe(LogLevelFilter filter, OnLogMessage handler) Subscribes with a filter; dispose the returned IDisposable to unsubscribe.
DebugLog.Subscribe(LogLevelFilter filter, OnLogMessageDetailed handler) Detailed variant that also receives the message's holes (ReadOnlyMemory<MessageHole>).
DebugLog.Log(string source, LogLevel level, string message) Writes a message.
DebugLog.IsWritingLog Whether anything is listening.
using MonoMod.Logs;

using var sub = DebugLog.Subscribe(LogLevelFilter.Warning | LogLevelFilter.Error,
    (source, time, level, message) => MyLogger.Write($"[{source}] {level}: {message}"));

Mod loaders typically forward MonoMod's log to their own console this way.

Other Useful Runtime Environment Variables

docs/Debugging.md lists CoreCLR variables that help when debugging crashes in hooked processes (on recent CoreCLR, COMPlus_ can be replaced by DOTNET_):

Variable Purpose
COMPlus_DbgEnableMiniDump=1 Write a crash dump on a crash (unhandled managed exception or internal runtime failure).
COMPlus_DbgMiniDumpName Dump file name.
COMPlus_DbgMiniDumpType Dump kind (4 is a full dump).
COMPlus_EnableDumpOnSigTerm=1 Also dump on SIGTERM.
COMPlus_LogEnable=1, COMPlus_LogFacility, COMPlus_LogFacility2, COMPlus_LogLevel CLR stress log.
DOTNET_TieredPGO, DOTNET_ReadPGOData, DOTNET_WritePGOData, DOTNET_PGODataPath Profile-guided optimization controls.

See Also