---
name: client-side-notification-logger
description: Provides a client-side logging utility that combines toast notifications with console logging for enhanced observability.
version: "1.0.0"
specialist: Sven
governance: OPEN
---

# Client-Side Notification Logger

This skill provides a reusable client-side logging utility that combines user-friendly toast notifications with detailed console logging. This approach enhances observability by providing immediate feedback to the user through toasts while retaining detailed logs for debugging.

## How to Implement

1.  **Install a Toast Notification Library:**

    Install a library like `sonner` for displaying toast notifications.

    ```bash
    npm install sonner
    # or
    yarn add sonner
    # or
    pnpm add sonner
    ```

2.  **Create the Logging Utility:**

    Create a client component (e.g., `use-notification-logger.tsx`) that exports a `useNotificationLogger` hook. This hook should:

    *   Accept an optional `logLevel` parameter (e.g., 'info', 'warn', 'error', 'debug') and a `toastOptions` object for configuring the toast.
    *   Return a `log` function that accepts a message string as input.
    *   The `log` function should:
        *   Display the message as a toast notification using the chosen library (e.g., `sonner`), configurable via `toastOptions`.
        *   Log the message to the console using `console.log`, but only if the `logLevel` is appropriate (e.g., only log 'error' messages if `logLevel` is 'error' or more permissive).

    ```typescript
    'use client';

    import { toast, ToastOptions } from 'sonner';
    import { useCallback } from 'react';

    type LogLevel = 'info' | 'warn' | 'error' | 'debug';

    interface UseNotificationLoggerProps {
      logLevel?: LogLevel;
      toastOptions?: ToastOptions;
    }

    export function useNotificationLogger({ logLevel = 'info', toastOptions }: UseNotificationLoggerProps = {}) {
      const log = useCallback((message: string, level: LogLevel = 'info') => {
        if (shouldLog(level, logLevel)) {
          if (process.env.NODE_ENV !== 'production') {
            console.log(`[${level.toUpperCase()}]: ${message}`);
          }

          if (level === 'error') {
            toast.error(message, toastOptions);
          } else if (level === 'warn') {
            toast.warning(message, toastOptions);
          }
          else {
            toast(message, toastOptions);
          }
        }
      }, [logLevel, toastOptions]);

      return { log };
    }

    function shouldLog(messageLevel: LogLevel, configuredLevel: LogLevel): boolean {
      const levels: { [key: string]: number } = {
        'debug': 0,
        'info': 1,
        'warn': 2,
        'error': 3,
      };

      return levels[messageLevel] >= levels[configuredLevel];
    }
    ```

3.  **Usage:**

    Import and use the `useNotificationLogger` hook in your client-side components.

    ```typescript
    'use client';

    import { useNotificationLogger } from './use-notification-logger';
    import { useState } from 'react';

    function MyComponent() {
      const { log } = useNotificationLogger({ logLevel: process.env.NEXT_PUBLIC_LOG_LEVEL as any || 'info', toastOptions: { duration: 5000 } });
      const [count, setCount] = useState(0);

      const handleClick = () => {
        log(`Button clicked! Count: ${count}`, 'info');
        setCount(count + 1);
        // Perform other actions
      };

      const handleWarning = () => {
        log('This is a warning message!', 'warn');
      };

       const handleError = () => {
        log('This is an error message!', 'error');
      };

      return (
        <>
          <button onClick={handleClick}>Click Me</button>
          <button onClick={handleWarning}>Show Warning</button>
          <button onClick={handleError}>Show Error</button>
        </>
      );
    }
    ```

## Benefits

*   **Improved User Experience:** Provides immediate feedback to the user through toast notifications.
*   **Enhanced Observability:** Combines toast notifications with console logging for detailed debugging information.
*   **Reusability:** Can be easily integrated into any client-side component.
*   **Configurable Logging Levels:** Control the verbosity of logging based on environment or application settings.
*   **Customizable Toast Notifications:** Configure the appearance and behavior of toast notifications.

## Considerations

*   Choose a toast notification library that aligns with your project's design and accessibility requirements.
*   Configure the `logLevel` based on the environment (e.g., more verbose logging in development, less verbose in production).  Use environment variables for configuration.
*   Implement error handling to gracefully handle potential issues with the toast notification library.
*   Be mindful of logging sensitive data.  Avoid logging any PII or secrets.
*   The `NODE_ENV !== 'production'` check prevents console logs in production builds, further reducing performance impact.


---
*Provisioned by Rigstate CLI. Do not modify manually.*