Skip to content
Justin Skiles edited this page Apr 17, 2020 · 1 revision

The SharpDL game engine allows you to inject whatever logging framework you want to use (provided that the framework implements a provider for the Microsoft.Extensions.Logging framework).

  1. Add the Microsoft.Extensions.Logging.Console NuGet package to your game project.

    dotnet add package Microsoft.Extensions.Logging.Console

  2. Update Program.cs to add console logging to the dependency injection container with filtering to whatever log level you prefer. Example below allows Trace and above.

    private static void ConfigureServices(ServiceCollection services)
    {
        services.AddSharpGame<MainGame>()
        .AddLogging(config => {
            config.AddConsole();
        })
        .Configure<LoggerFilterOptions>(options => {
            options.AddFilter<ConsoleLoggerProvider>(null, LogLevel.Trace);
        });
    }
  3. Add an injected ILogger<MainGame> dependency to your MainGame constructor.

    private readonly IGameEngine engine;
    private readonly ILogger<MainGame> logger;
    
    public MainGame(IGameEngine engine, ILogger<MainGame> logger)
    {
    	this.engine = engine;
    	this.logger = logger;
    	engine.Initialize = () => Initialize();
    	engine.LoadContent = () => LoadContent();
    	engine.Draw = (gameTime) => Draw(gameTime);
    	engine.UnloadContent = () => UnloadContent(gameTime);
    }
  4. Use the logger in your MainGame class where you see fit. For example, this example logs when your injected implementation of the LoadContent method finishes.

    private readonly ILogger<MainGame> logger;
    
    private void LoadContent()
    {
    	Surface surface = new Surface("image.png", SurfaceType.PNG);
    	texture = new Texture(renderer, surface);
    	logger.LogInformation("LoadContent finished.");
    }
  5. Build and run to see logs that look like below. These are trace events occurring in the engine.

    dotnet build
    dotnet run
    
    trce: SharpDL.Graphics.WindowFactory[0]
          Window created. Title = Example 0 - Sandbox, X = 100, Y = 100, Width = 1280, Height = 720, Handle = 2031943582128.
    trce: SharpDL.Graphics.RendererFactory[0]
          Renderer created. Handle = 2031943582928, Window Title = Example 0 - Sandbox, Window Handle = 2031943582128.
    trce: SharpDL.GameEngine[0]
          SDL_Event: SDL_AUDIODEVICEADDED
Clone this wiki locally