> For the complete documentation index, see [llms.txt](https://docs-siticoneframework.gitbook.io/home/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-siticoneframework.gitbook.io/home/net-framework-or-net-core-ui/input-controls/siticone-toggleswitch/logging-and-diagnostics.md).

# Logging and Diagnostics

## **Overview**

The `SiticoneToggleSwitch` provides built-in **logging and diagnostic support** to help developers **track state changes, debug issues, and log user interactions** efficiently. This guide covers **logging mechanisms, best practices, and diagnostic tools** available in the control.

***

### **1. Logging System**

#### **1.1 IToggleSwitchLogger Interface**

The control supports **custom logging implementations** via the `IToggleSwitchLogger` interface.

| **Interface**         | **Description**                                            |
| --------------------- | ---------------------------------------------------------- |
| `IToggleSwitchLogger` | Defines a **custom logger** to track switch state changes. |

**Method Signature**

```csharp
public interface IToggleSwitchLogger
{
    void Log(string message);
}
```

***

#### **1.2 File-Based Logging**

The `FileToggleSwitchLogger` is a **prebuilt logger** that logs toggle events to a text file.

| **Class**                | **Description**                    |
| ------------------------ | ---------------------------------- |
| `FileToggleSwitchLogger` | Logs messages to a specified file. |

**Usage Example**

```csharp
// Initialize the logger
var logger = new SiticoneToggleSwitch.FileToggleSwitchLogger("toggle_log.txt");

// Assign to the control
myToggleSwitch.Logger = logger;

// Log a custom message
logger.Log("Toggle Switch Initialized.");
```

***

### **2. State Change Tracking**

#### **2.1 Toggle Events**

The control provides events for **tracking toggle state changes**.

| **Event**       | **Description**                                           |
| --------------- | --------------------------------------------------------- |
| `Toggled`       | Fired when the switch **changes state** (ON/OFF).         |
| `StateChanging` | Triggered **before** the state changes (can be canceled). |
| `StateChanged`  | Fired **after** the state has changed.                    |

**Usage Example**

```csharp
myToggleSwitch.Toggled += (sender, e) =>
{
    Console.WriteLine($"Toggle state changed: {(e.IsOn ? "On" : "Off")}");
};
```

***

#### **2.2 Preventing State Changes**

The `StateChangingEventArgs` allows **preventing unwanted state changes**.

| **Property**   | **Type** | **Description**                       |
| -------------- | -------- | ------------------------------------- |
| `CurrentState` | `bool`   | The **existing** state before change. |
| `NewState`     | `bool`   | The **requested** new state.          |
| `Cancel`       | `bool`   | Set `true` to **prevent** the change. |

**Usage Example**

```csharp
myToggleSwitch.StateChanging += (sender, e) =>
{
    if (!UserHasPermission)
    {
        e.Cancel = true; // Prevent state change
        Console.WriteLine("Toggle action denied.");
    }
};
```

***

### **3. Theme Change Detection**

The `SiticoneToggleSwitch` can track **system-wide theme changes** and log them.

| **Event**            | **Description**                           |
| -------------------- | ----------------------------------------- |
| `SystemThemeChanged` | Fired when the **Windows theme** changes. |

**Usage Example**

```csharp
myToggleSwitch.SystemThemeChanged += (sender, e) =>
{
    Console.WriteLine($"System theme changed to: {e.NewTheme}");
};
```

***

### **4. When to Use These Features?** ✅

| **Feature**          | **Use Case**                                        |
| -------------------- | --------------------------------------------------- |
| `Logger`             | **Track user interactions** for debugging.          |
| `Toggled Event`      | Execute **actions on state change**.                |
| `StateChanging`      | **Restrict toggling** based on conditions.          |
| `SystemThemeChanged` | Monitor **system theme changes** for UI adaptation. |

***

### **5. Common Pitfalls & Design Considerations** 🛑

| **Pitfall**                                | **Cause**                                      | **Solution**                                     |
| ------------------------------------------ | ---------------------------------------------- | ------------------------------------------------ |
| **Logs not saving**                        | Missing file path in `FileToggleSwitchLogger`. | Ensure **valid path** is set.                    |
| **Event handlers not triggering**          | Not attached properly.                         | Use `+=` to **subscribe to events**.             |
| **StateChanging doesn’t prevent toggling** | `Cancel` flag not set.                         | **Set `e.Cancel = true;`** in the event handler. |
| **Theme change detection fails**           | `TrackDeviceTheme = false`.                    | **Enable `TrackDeviceTheme`**.                   |

***

### **6. Points Learned** 🎯

✅ **Use `Logger` for debugging toggle interactions.**\
✅ **Attach `Toggled` and `StateChanged` for real-time updates.**\
✅ **Use `StateChanging` to restrict state changes.**\
✅ **Monitor `SystemThemeChanged` for adaptive UI.**

***

### **7. Review Checklist** ✔️

| **Item**                                    | **Check** |
| ------------------------------------------- | --------- |
| Are all toggle interactions **logged**?     | ✅         |
| Is `StateChanging` used for **validation**? | ✅         |
| Is logging **enabled for debugging**?       | ✅         |
| Are **event handlers properly assigned**?   | ✅         |
| Is **theme tracking active** (if needed)?   | ✅         |

***

### **8. Summary** 📌

#### **8.1 Feature Summary**

| **Feature**              | **Type**    | **Description**                             |
| ------------------------ | ----------- | ------------------------------------------- |
| `Logger`                 | `interface` | Custom logging system.                      |
| `FileToggleSwitchLogger` | `class`     | Logs to a file.                             |
| `Toggled`                | `event`     | Fires when toggle state changes.            |
| `StateChanging`          | `event`     | Fires **before** state change (cancelable). |
| `SystemThemeChanged`     | `event`     | Detects system-wide theme updates.          |

***

#### **8.2 Key Takeaways**

| **Key Takeaway**                                       | **Description**                                                   |
| ------------------------------------------------------ | ----------------------------------------------------------------- |
| **Logging enables better debugging & analytics.**      | Helps track **toggle interactions** and diagnose issues.          |
| **Events allow real-time tracking & state control.**   | Provides **instant feedback** on toggle state changes.            |
| **StateChanging can restrict toggling when needed.**   | Use it to **prevent unintended state changes**.                   |
| **Use SystemThemeChanged for seamless UI adaptation.** | Ensures the control **matches system theme changes dynamically**. |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs-siticoneframework.gitbook.io/home/net-framework-or-net-core-ui/input-controls/siticone-toggleswitch/logging-and-diagnostics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
