Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 44 additions & 14 deletions examples/Logging/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

using Iceoryx2;
using System;
using System.IO;

class Program
{
Expand All @@ -34,26 +35,22 @@ static void Main(string[] args)
Console.WriteLine("Usage: dotnet run [basic|custom|file]");
Console.WriteLine();
Console.WriteLine("Examples:");
Console.WriteLine(" dotnet run basic - Use console logger with environment variable");
Console.WriteLine(" dotnet run basic - Use default console logger with environment variable");
Console.WriteLine(" dotnet run custom - Use custom logger callback");
Console.WriteLine(" dotnet run file - Use file logger");
Console.WriteLine(" dotnet run file - Use custom file logger (via SetLogger callback)");
}
}

static void RunBasicLoggingExample()
{
Console.WriteLine("=== Basic Logging Example ===");
Console.WriteLine();
Console.WriteLine("Note: Starting with iceoryx2 v0.8.0, the console logger is enabled by default.");
Console.WriteLine();

// Set log level from environment variable IOX2_LOG_LEVEL (or default to Info)
Iox2Log.SetLogLevelFromEnvOrDefault();

// Use the built-in console logger
if (Iox2Log.UseConsoleLogger())
{
Console.WriteLine("Console logger initialized successfully");
}

Console.WriteLine($"Current log level: {Iox2Log.GetLogLevel()}");
Console.WriteLine();

Expand Down Expand Up @@ -151,25 +148,57 @@ static void RunCustomLoggerExample()

static void RunFileLoggerExample()
{
Console.WriteLine("=== File Logger Example ===");
Console.WriteLine("=== File Logger Example (via Custom Logger) ===");
Console.WriteLine();
Console.WriteLine("Note: Starting with iceoryx2 v0.8.0, file logging requires rebuilding");
Console.WriteLine("iceoryx2 with specific feature flags. This example demonstrates");
Console.WriteLine("implementing file logging using a custom logger callback instead.");
Console.WriteLine();

var logFile = "/tmp/iceoryx2_csharp.log";

// Use file logger
if (Iox2Log.UseFileLogger(logFile))
// Create or truncate the log file
using (var writer = new StreamWriter(logFile, append: false))
{
writer.WriteLine($"=== iceoryx2 Log File - Started at {DateTime.Now:yyyy-MM-dd HH:mm:ss} ===");
}

// Use a custom logger that writes to file
var success = Iox2Log.SetLogger((level, origin, message) =>
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
var levelStr = level.ToString().ToUpper().PadRight(5);
var logLine = string.IsNullOrEmpty(origin)
? $"[{timestamp}] [{levelStr}] {message}"
: $"[{timestamp}] [{levelStr}] {origin} - {message}";

// Write to file
try
{
File.AppendAllText(logFile, logLine + Environment.NewLine);
}
catch (Exception ex)
{
Console.Error.WriteLine($"Failed to write to log file: {ex.Message}");
}

// Also write to console for visibility
Console.WriteLine(logLine);
});

if (success)
{
Console.WriteLine($"File logger initialized: {logFile}");
Console.WriteLine($"Custom file logger initialized: {logFile}");
}
else
{
Console.WriteLine("Failed to initialize file logger");
Console.WriteLine("Failed to set custom logger (may have been set already)");
return;
}

// Set log level
Iox2Log.SetLogLevel(LogLevel.Debug);
Console.WriteLine($"Iox2Log level set to: {Iox2Log.GetLogLevel()}");
Console.WriteLine($"Log level set to: {Iox2Log.GetLogLevel()}");
Console.WriteLine();

// Write some log messages
Expand All @@ -180,6 +209,7 @@ static void RunFileLoggerExample()
Iox2Log.Write(LogLevel.Error, "FileLogging", "Error message to file");

// Create a node to generate library logs
Console.WriteLine();
Console.WriteLine("Creating iceoryx2 node (logs will be written to file)...");
var node = NodeBuilder.New()
.Name("file_logging_example")
Expand Down
84 changes: 58 additions & 26 deletions examples/Logging/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,36 @@

This example demonstrates how to use the iceoryx2 logging functionality in C#.

## Logging Backend Changes in v0.8.0

Starting with iceoryx2 v0.8.0, the logging backend has changed:

* **Console logger is now enabled by default** - No explicit initialization required
* **File logger requires rebuilding iceoryx2** with specific feature flags
* **Custom loggers** can be set at runtime using `SetLogger()`

### Available Loggers (via feature flags on iceoryx2-loggers crate)

1. **console** - outputs log messages to the console (default)
2. **buffer** - outputs log messages to a buffer
3. **file** - outputs log messages to a file
4. **log** - utilizes the `log` crate
5. **tracing** - utilizes the `tracing` crate

### Enabling File Logger

To use the native file logger, rebuild iceoryx2 with:

```bash
cargo build --package iceoryx2-ffi-c --features iceoryx2-loggers/std --features iceoryx2-loggers/file --no-default-features --release
```

Alternatively, use a custom logger callback (demonstrated in this example).

## Features

* **Console Logging**: Use the built-in console logger
* **File Logging**: Write logs to a file
* **Console Logging**: Enabled by default in iceoryx2 v0.8.0+
* **Custom File Logging**: Implement file logging via custom logger callback
* **Custom Logger**: Implement custom log formatting and handling
* **Log Levels**: Control verbosity with log levels (Trace, Debug, Info, Warn,
Error, Fatal)
Expand All @@ -16,20 +42,20 @@ This example demonstrates how to use the iceoryx2 logging functionality in C#.
### Basic Console Logging

```bash
dotnet run basic
dotnet run --framework net9.0 -- basic
```

This example shows:

* Setting log level from environment variable
* Using the console logger
* Using the default console logger (enabled automatically in v0.8.0+)
* Writing messages at different log levels
* Seeing library-generated logs

### Custom Logger with Color

```bash
dotnet run custom
dotnet run --framework net9.0 -- custom
```

This example demonstrates:
Expand All @@ -38,16 +64,17 @@ This example demonstrates:
* Adding timestamps and colored output
* Formatting log messages

### File Logging
### File Logging (via Custom Logger)

```bash
dotnet run file
dotnet run --framework net9.0 -- file
```

This example shows:

* Implementing file logging using a custom logger callback
* Writing logs to a file (`/tmp/iceoryx2_csharp.log`)
* Viewing library logs in the file
* Viewing library logs in both console and file

## Log Levels

Expand All @@ -67,66 +94,71 @@ Set the log level using the `IOX2_LOG_LEVEL` environment variable:
```bash
# Set to Debug level
export IOX2_LOG_LEVEL=DEBUG
dotnet run basic
dotnet run --framework net9.0 -- basic

# Set to Trace level (most verbose)
export IOX2_LOG_LEVEL=TRACE
dotnet run basic
dotnet run --framework net9.0 -- basic

# Set to Warn level (less verbose)
export IOX2_LOG_LEVEL=WARN
dotnet run basic
dotnet run --framework net9.0 -- basic
```

## API Usage

### Basic Logging
### Basic Logging (v0.8.0+)

```csharp
using Iceoryx2;

// Use console logger
Log.UseConsoleLogger();
// Console logger is enabled by default - no initialization needed!

// Set log level
Log.SetLogLevel(LogLevel.Debug);
Iox2Log.SetLogLevel(LogLevel.Debug);

// Write log message
Log.Write(LogLevel.Info, "MyApp", "Application started");
Iox2Log.Write(LogLevel.Info, "MyApp", "Application started");
```

### Environment-based Configuration

```csharp
// Set log level from IOX2_LOG_LEVEL environment variable, default to Info
Log.SetLogLevelFromEnvOrDefault();
Iox2Log.SetLogLevelFromEnvOrDefault();

// Or with custom default
Log.SetLogLevelFromEnvOr(LogLevel.Debug);
Iox2Log.SetLogLevelFromEnvOr(LogLevel.Debug);
```

### Custom Logger

```csharp
// Set custom logger (can only be called once)
bool success = Log.SetLogger((level, origin, message) =>
// Set custom logger (can only be called once, before any log messages)
bool success = Iox2Log.SetLogger((level, origin, message) =>
{
Console.WriteLine($"[{level}] {origin}: {message}");
});
```

### File Logger
### Custom File Logger

```csharp
// Write logs to file
Log.UseFileLogger("/tmp/myapp.log");
Log.Write(LogLevel.Info, "MyApp", "This goes to the file");
// Implement file logging via custom logger callback
Iox2Log.SetLogger((level, origin, message) =>
{
var logLine = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
File.AppendAllText("/tmp/myapp.log", logLine + Environment.NewLine);
});
Iox2Log.Write(LogLevel.Info, "MyApp", "This goes to the file");
```

## Notes

* The custom logger can only be set once and must be set before any log messages
* The console logger is enabled by default in iceoryx2 v0.8.0+
* Custom loggers can only be set once and must be set before any log messages
are created
* The built-in loggers (console/file) handle this restriction automatically
* Library-generated logs (from iceoryx2 itself) will use the configured logger
* Origin can be null or empty if not needed
* For native file logging support, rebuild iceoryx2 with the appropriate
feature flags
5 changes: 5 additions & 0 deletions examples/LoggingIntegration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ This example demonstrates how to integrate iceoryx2's internal logging with the
Microsoft.Extensions.Logging framework, allowing you to see iceoryx2's debug
logs through your existing logging infrastructure.

> **Note:** Starting with iceoryx2 v0.8.0, the console logger is enabled by
> default. The integration examples in this project use `SetLogger()` to
> redirect logs to Microsoft.Extensions.Logging, which continues to work
> as before.

## Features

The example showcases **4 different logging approaches**:
Expand Down
2 changes: 1 addition & 1 deletion iceoryx2
Submodule iceoryx2 updated 1170 files
Loading