Przejdź do treści

Debugowanie aplikacji

Debugowanie Frontend (Angular)

Browser DevTools

Chrome DevTools (F12):

  1. Console
  2. Błędy JavaScript/TypeScript
  3. console.log() statements
  4. Nieprzechycone wyjątki

  5. Sources

  6. Breakpointy w kodzie TypeScript
  7. Step through code (F10, F11)
  8. Watch variables
  9. Call stack

  10. Network

  11. HTTP requests/responses
  12. API call timings
  13. Status codes
  14. Request/response payloads

  15. Application

  16. Local Storage
  17. Session Storage
  18. Cookies
  19. Service Workers

VS Code Debugger

Konfiguracja .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Angular Debug",
      "url": "http://localhost:4200",
      "webRoot": "${workspaceFolder}",
      "sourceMapPathOverrides": {
        "webpack:/*": "${webRoot}/*"
      }
    }
  ]
}

Użycie: 1. Uruchom npm start 2. W VS Code: F5 lub Run → Start Debugging 3. Ustaw breakpoint w kodzie (kliknij obok numeru linii) 4. Wykonaj akcję w aplikacji 5. Debugger zatrzyma się na breakpoincie

Angular DevTools

Instalacja: - Chrome: Angular DevTools Extension - Firefox: Angular DevTools Extension

Funkcje: - Component tree inspector - Change detection profiler - Dependency injection tree - Route tree

Redux DevTools (NGXS)

Instalacja: Redux DevTools Extension

Użycie: 1. Otwórz DevTools → Redux tab 2. Zobacz wszystkie dispatched actions 3. Time-travel debugging (cofanie/przewijanie state) 4. Inspect state diff po każdej akcji

Debugowanie State Management

// W komponencie
import { Store } from '@ngxs/store';

constructor(private store: Store) {
  // Log całego state
  console.log('Current state:', this.store.snapshot());

  // Log konkretnego slice
  console.log('Budgets:', this.store.selectSnapshot(BudgetState));
}

Logging

// W services
import { environment } from '@msk/environment';

export class MyService {
  private log(message: string, data?: any) {
    if (!environment.production) {
      console.log(`[MyService] ${message}`, data);
    }
  }

  someMethod() {
    this.log('Method called', { param: value });
  }
}

Debugowanie API Calls

// W interceptorze (dla wszystkich requestów)
intercept(req: HttpRequest<any>, next: HttpHandler) {
  console.log('Request:', {
    url: req.url,
    method: req.method,
    body: req.body,
    headers: req.headers
  });

  return next.handle(req).pipe(
    tap(
      event => console.log('Response:', event),
      error => console.error('Error:', error)
    )
  );
}

Debugowanie Backend (.NET)

VS Code Debugger

Konfiguracja .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": ".NET Core Launch (web)",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      "program": "${workspaceFolder}/Masaku.API/bin/Debug/net6.0/Masaku.API.dll",
      "args": [],
      "cwd": "${workspaceFolder}/Masaku.API",
      "stopAtEntry": false,
      "serverReadyAction": {
        "action": "openExternally",
        "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
      },
      "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "sourceFileMap": {
        "/Views": "${workspaceFolder}/Views"
      }
    },
    {
      "name": ".NET Core Attach",
      "type": "coreclr",
      "request": "attach"
    }
  ]
}

Użycie: 1. Otwórz projekt w VS Code 2. Ustaw breakpoint w kontrollerze/serwisie 3. F5 lub Run → Start Debugging 4. Wykonaj request z frontendu lub Postmana 5. Debugger zatrzyma się na breakpoincie

Visual Studio (Windows)

  1. Otwórz masaku-api.sln
  2. Ustaw breakpoint (F9)
  3. Uruchom z debugowaniem (F5)
  4. Wykonaj request
  5. Używaj:
  6. F10 - Step Over
  7. F11 - Step Into
  8. Shift+F11 - Step Out
  9. F5 - Continue

Logging

Serilog configuration w appsettings.Development.json:

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Information",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "logs/log-.txt",
          "rollingInterval": "Day"
        }
      }
    ]
  }
}

W kodzie:

public class MyController : ControllerBase
{
    private readonly ILogger<MyController> _logger;

    public MyController(ILogger<MyController> logger)
    {
        _logger = logger;
    }

    public IActionResult Get(int id)
    {
        _logger.LogDebug("Getting item {Id}", id);

        try
        {
            var item = _service.GetById(id);
            _logger.LogInformation("Found item {Id}: {Name}", id, item.Name);
            return Ok(item);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting item {Id}", id);
            throw;
        }
    }
}

SQL Profiling

Entity Framework logging:

// W DbContext lub Startup.cs
optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information)
              .EnableSensitiveDataLogging(); // Tylko dla developmentu!

SQL Server Profiler: 1. Połącz się z localhost,1433 2. Start trace 3. Wykonaj operację w aplikacji 4. Zobacz wykonane queries

Alternatywnie - DBeaver: 1. Window → Show View → Query Manager 2. Zobacz ostatnie queries na serwerze

API Testing z Postman/Insomnia

Import Swagger do Postmana: 1. Otwórz http://localhost:5000/swagger/v1/swagger.json 2. W Postmanie: Import → Link 3. Wklej URL 4. Import

Testowanie endpointów:

# Przykładowy request
curl -X GET "http://localhost:5000/api/budgets" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json"

Debugowanie End-to-End

Scenariusz: "Dodaj budżet nie działa"

Krok 1: Frontend 1. Otwórz DevTools → Network 2. Kliknij "Dodaj budżet" 3. Wypełnij formularz 4. Kliknij "Zapisz" 5. Sprawdź Network tab: - Czy POST request został wysłany? - Jaki status code? (200, 400, 500?) - Co jest w response body?

Krok 2: Backend 1. Sprawdź logi API w terminalu 2. Znajdź POST /api/budgets request 3. Sprawdź czy dotarł do controllera 4. Ustaw breakpoint w kontrollerze i powtórz

Krok 3: Database

-- Sprawdź czy dane zapisały się w bazie
SELECT * FROM Budgets
ORDER BY CreatedAt DESC;

Krok 4: State Management 1. Otwórz Redux DevTools 2. Znajdź akcję AddBudget 3. Sprawdź state przed i po akcji 4. Sprawdź czy reducer zadziałał poprawnie

Performance Debugging

Frontend Performance

Chrome DevTools → Performance: 1. Kliknij Record 2. Wykonaj akcję (np. otwarcie listy budżetów) 3. Stop recording 4. Analizuj: - Scripting time - Rendering time - Loading time

Angular DevTools → Profiler: 1. Start recording 2. Wykonaj akcję 3. Zobacz które komponenty się renderują 4. Zoptymalizuj change detection (OnPush)

Backend Performance

Application Insights (jeśli skonfigurowane): - Request durations - Dependency calls (SQL, HTTP) - Exceptions

Manual timing:

var stopwatch = Stopwatch.StartNew();
var result = _service.ExpensiveOperation();
stopwatch.Stop();
_logger.LogInformation("Operation took {Ms}ms", stopwatch.ElapsedMilliseconds);

SQL Performance:

-- Sprawdź slow queries
SELECT TOP 10
    qs.execution_count,
    qs.total_elapsed_time / qs.execution_count AS avg_time,
    qt.text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
ORDER BY avg_time DESC;

Narzędzia pomocnicze

Frontend

  • Augury - Angular debugging (przestarzałe, użyj Angular DevTools)
  • Lighthouse - Performance audit
  • React DevTools - Nie, to Angular 😊

Backend

  • Seq - Structured logging server
  • MiniProfiler - SQL profiling
  • BenchmarkDotNet - Performance benchmarking

Database

  • DBeaver - Universal database tool
  • SQL Server Management Studio - Microsoft's official tool
  • Azure Data Studio - Cross-platform SQL tool

Troubleshooting common issues

"Nie widzę źródeł w debuggerze"

  • Sprawdź czy source maps są generowane
  • W angular.json: "sourceMap": true
  • W tsconfig.json: "sourceMap": true

"Breakpoint nie zatrzymuje wykonania"

  • Sprawdź czy kod jest kompilowany w trybie Debug (nie Release)
  • Sprawdź czy jesteś w odpowiednim procesie (Attach to Process)
  • Restart debuggera

"Logi nie pokazują się"

  • Sprawdź poziom logowania (Debug, Information, Warning, Error)
  • Frontend: usuń console.log() w production builds
  • Backend: sprawdź Serilog configuration

Dalsze kroki

Dalsze zasoby