diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index 2dc27744..4b1bcea3 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -1,17 +1,19 @@ package main import ( - "log" + "log/slog" "os" - "strconv" - - "baron-sso-backend/internal/handler" + "strconv" + "time" + + "github.com/bwmarrin/snowflake" + "baron-sso-backend/internal/handler" + "baron-sso-backend/internal/logger" "baron-sso-backend/internal/repository" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "github.com/gofiber/fiber/v2/middleware/encryptcookie" - "github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/recover" "github.com/gofiber/fiber/v2/middleware/requestid" ) @@ -24,13 +26,25 @@ func getEnv(key, fallback string) string { } func main() { + // 0. Initialize Logger + logger.Init(logger.Config{ + ServiceName: "baron-sso", + Environment: getEnv("GO_ENV", "dev"), + }) + + // Initialize Snowflake Node (Node 2 for Baron) + node, err := snowflake.NewNode(2) + if err != nil { + slog.Error("Failed to initialize snowflake node", "error", err) + os.Exit(1) + } + // 1. Log Config on Startup - log.Println("==========================================") - log.Println("Starting Baron SSO Backend...") - log.Printf("FRONTEND_URL: %s", getEnv("FRONTEND_URL", "http://ssologin.hmac.kr")) - log.Printf("REDIS_ADDR: %s", getEnv("REDIS_ADDR", "redis:6379")) - log.Printf("DESCOPE_ID: %s", getEnv("DESCOPE_PROJECT_ID", "not-set")) - log.Println("==========================================") + slog.Info("Starting Baron SSO Backend", + "frontend_url", getEnv("FRONTEND_URL", "http://ssologin.hmac.kr"), + "redis_addr", getEnv("REDIS_ADDR", "redis:6379"), + "descope_id", getEnv("DESCOPE_PROJECT_ID", "not-set"), + ) // 2. Initialize DB Connections chHost := getEnv("CLICKHOUSE_HOST", "localhost") @@ -41,8 +55,7 @@ func main() { auditRepo, err := repository.NewClickHouseRepository(chHost, chPort, chUser, chPass, chDB) if err != nil { - log.Printf("Warning: Failed to connect to ClickHouse: %v. Audit logs will fail.", err) - // Proceeding mostly for Dev purposes, but in Prod should generally fail or fallback. + slog.Warn("Failed to connect to ClickHouse. Audit logs will fail.", "error", err) } // 2. Initialize Handlers @@ -52,17 +65,42 @@ func main() { // 3. Initialize Fiber app := fiber.New(fiber.Config{ AppName: "Baron SSO Backend", + DisableStartupMessage: true, // Clean logs }) // Middleware app.Use(requestid.New(requestid.Config{ Generator: func() string { - return handler.GenerateSecureToken(4) // 8 chars hex + return node.Generate().String() }, })) - app.Use(logger.New(logger.Config{ - Format: "[${time}] ${status} - ${method} ${path}\n", - })) + + // [Standardized] HTTP Request Logger Middleware using slog + app.Use(func(c *fiber.Ctx) error { + start := time.Now() + + // Handle request + err := c.Next() + + // Log after request + latency := time.Since(start) + + msg := "http_request" + if err != nil { + msg = "http_request_error" + } + + slog.Info(msg, + "status", c.Response().StatusCode(), + "method", c.Method(), + "path", c.Path(), + "latency", latency.String(), + "ip", c.IP(), + "req_id", c.GetRespHeader(fiber.HeaderXRequestID), + ) + return err + }) + app.Use(recover.New()) app.Use(cors.New(cors.Config{ AllowOrigins: "*", // Adjust in production @@ -100,21 +138,52 @@ func main() { // Webhook for Descope Generic Email Gateway (Fake Email Strategy) auth.Post("/webhooks/descope-email", authHandler.HandleDescopeEmailRelay) - // Client Logging Route (For Debugging) + // Client Logging Route (Standardized & Flattened) api.Post("/client-log", func(c *fiber.Ctx) error { type LogReq struct { - Level string `json:"level"` - Message string `json:"message"` + Level string `json:"level"` + Message string `json:"message"` + Data map[string]interface{} `json:"data,omitempty"` } var req LogReq if err := c.BodyParser(&req); err != nil { return c.SendStatus(fiber.StatusBadRequest) } - log.Printf("[CLIENT-LOG] [%s] %s", req.Level, req.Message) + + // Prepare attributes for flattening + attrs := []any{ + slog.String("source", "client"), + } + for k, v := range req.Data { + // Skip svc if it's already set by the global logger to avoid confusion, + // or keep it as client_svc + if k == "svc" { + attrs = append(attrs, slog.Any("client_svc", v)) + } else { + attrs = append(attrs, slog.Any(k, v)) + } + } + + // Map and log with correct level + var level slog.Level + switch req.Level { + case "SEVERE", "ERROR": + level = slog.LevelError + case "WARNING", "WARN": + level = slog.LevelWarn + default: + level = slog.LevelInfo + } + + slog.Log(c.Context(), level, req.Message, attrs...) return c.SendStatus(fiber.StatusOK) }) // Start Server port := getEnv("PORT", "3000") - log.Fatal(app.Listen(":" + port)) + slog.Info("Server listening", "port", port) + if err := app.Listen(":" + port); err != nil { + slog.Error("Server failed to start", "error", err) + os.Exit(1) + } } diff --git a/backend/go.mod b/backend/go.mod index 98e334bf..23af349f 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -12,6 +12,7 @@ require ( require ( github.com/ClickHouse/ch-go v0.69.0 // indirect github.com/andybalholm/brotli v1.2.0 // indirect + github.com/bwmarrin/snowflake v0.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect diff --git a/backend/go.sum b/backend/go.sum index a74347da..f23f6c51 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -4,6 +4,8 @@ github.com/ClickHouse/clickhouse-go/v2 v2.42.0 h1:MdujEfIrpXesQUH0k0AnuVtJQXk6RZ github.com/ClickHouse/clickhouse-go/v2 v2.42.0/go.mod h1:riWnuo4YMVdajYll0q6FzRBomdyCrXyFY3VXeXczA8s= github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0= +github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/backend/internal/logger/logger.go b/backend/internal/logger/logger.go new file mode 100644 index 00000000..d74b0a60 --- /dev/null +++ b/backend/internal/logger/logger.go @@ -0,0 +1,49 @@ +package logger + +import ( + "log/slog" + "os" + "strings" +) + +// Config holds the logger configuration +type Config struct { + ServiceName string + Environment string // "dev", "local", "production" +} + +// Init initializes the global logger with slog. +// It detects the environment to switch between TextHandler (dev) and JSONHandler (prod). +func Init(cfg Config) { + var handler slog.Handler + + opts := &slog.HandlerOptions{ + // Default level + Level: slog.LevelInfo, + // Customize attributes (Time format) + ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { + if a.Key == slog.TimeKey { + return slog.String(a.Key, a.Value.Time().Format("2006-01-02 15:04:05")) + } + return a + }, + } + + // Adjust level and format based on environment + env := strings.ToLower(cfg.Environment) + if env == "dev" || env == "local" || env == "development" { + opts.Level = slog.LevelDebug + handler = slog.NewTextHandler(os.Stdout, opts) + } else { + // Production defaults to JSON + handler = slog.NewJSONHandler(os.Stdout, opts) + } + + // Create logger with common attributes + logger := slog.New(handler).With( + slog.String("svc", cfg.ServiceName), + ) + + // Set as global default logger + slog.SetDefault(logger) +} diff --git a/frontend/lib/core/services/auth_proxy_service.dart b/frontend/lib/core/services/auth_proxy_service.dart index 6b6d4aa5..1308a69f 100644 --- a/frontend/lib/core/services/auth_proxy_service.dart +++ b/frontend/lib/core/services/auth_proxy_service.dart @@ -99,19 +99,28 @@ class AuthProxyService { } } - static Future logError(String message) async { + static Future sendLog(String level, String message, {Map? data}) async { final url = Uri.parse('$_baseUrl/api/v1/client-log'); try { await http.post( url, headers: {'Content-Type': 'application/json'}, body: jsonEncode({ - 'level': 'ERROR', + 'level': level, 'message': message, + if (data != null) 'data': data, }), ); } catch (_) { // Ignore logging errors to prevent loops } } + + static Future logError(String message, {dynamic error, StackTrace? stackTrace}) async { + final data = {}; + if (error != null) data['error'] = error.toString(); + if (stackTrace != null) data['stack'] = stackTrace.toString(); + + await sendLog('ERROR', message, data: data); + } } diff --git a/frontend/lib/core/services/logger_service.dart b/frontend/lib/core/services/logger_service.dart new file mode 100644 index 00000000..b9dd32a7 --- /dev/null +++ b/frontend/lib/core/services/logger_service.dart @@ -0,0 +1,86 @@ +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:logging/logging.dart' as std_log; +import 'package:logger/logger.dart' as pretty_log; +import 'auth_proxy_service.dart'; + +/// Global Logger Service for Baron SSO Frontend +class LoggerService { + static final LoggerService _instance = LoggerService._internal(); + factory LoggerService() => _instance; + + late final pretty_log.Logger _prettyLogger; + + LoggerService._internal() { + // 1. Initialize Pretty Logger for Dev + _prettyLogger = pretty_log.Logger( + printer: pretty_log.PrettyPrinter( + methodCount: 0, + errorMethodCount: 8, + lineLength: 120, + colors: true, + printEmojis: true, + dateTimeFormat: pretty_log.DateTimeFormat.onlyTimeAndSinceStart, + ), + ); + + // 2. Configure Standard Logger (logging package) + std_log.Logger.root.level = kReleaseMode ? std_log.Level.INFO : std_log.Level.ALL; + + std_log.Logger.root.onRecord.listen((record) { + if (kReleaseMode) { + // [Production] Log as JSON + _logJson(record); + } else { + // [Development] Log using Pretty Printer + _logPretty(record); + } + }); + } + + /// Initialize the logger. Call this in main.dart + static void init() { + // Accessing the instance triggers the constructor + LoggerService(); + std_log.Logger('BaronSSO').info('Logger initialized'); + } + + void _logPretty(std_log.LogRecord record) { + if (record.level >= std_log.Level.SEVERE) { + _prettyLogger.e(record.message, error: record.error, stackTrace: record.stackTrace); + } else if (record.level >= std_log.Level.WARNING) { + _prettyLogger.w(record.message); + } else if (record.level >= std_log.Level.INFO) { + _prettyLogger.i(record.message); + } else { + _prettyLogger.d(record.message); + } + } + + void _logJson(std_log.LogRecord record) { + final logData = { + 'time': record.time.toUtc().toIso8601String(), // Use UTC for consistency + 'level': record.level.name, + 'msg': record.message, + 'svc': 'baron-frontend', + if (record.error != null) 'error': record.error.toString(), + if (record.stackTrace != null) 'stack': record.stackTrace.toString(), + }; + + // 1. Print to Browser Console (F12) + debugPrint(jsonEncode(logData)); + + // 2. Relay to Backend (Docker Terminal) + if (record.level >= std_log.Level.INFO) { + AuthProxyService.sendLog( + record.level.name, + record.message, + data: { + 'client_time': record.time.toUtc().toIso8601String(), + 'logger': record.loggerName, + if (record.error != null) 'error': record.error.toString(), + }, + ); + } + } +} diff --git a/frontend/lib/main.dart b/frontend/lib/main.dart index cddaf7ab..156b3fbd 100644 --- a/frontend/lib/main.dart +++ b/frontend/lib/main.dart @@ -9,18 +9,28 @@ import 'package:flutter_web_plugins/url_strategy.dart'; import 'features/auth/presentation/login_screen.dart'; import 'features/dashboard/presentation/dashboard_screen.dart'; import 'core/services/auth_proxy_service.dart'; +import 'core/services/logger_service.dart'; +import 'package:logging/logging.dart'; + +final _log = Logger('Main'); void main() async { WidgetsFlutterBinding.ensureInitialized(); usePathUrlStrategy(); + + // 0. Initialize Logger + LoggerService.init(); // 1. Global Error Handling FlutterError.onError = (details) { FlutterError.presentError(details); + _log.severe("FLUTTER_ERROR", details.exception, details.stack); + // Also send to backend if needed AuthProxyService.logError("FLUTTER_ERROR: ${details.exception}\n${details.stack}"); }; PlatformDispatcher.instance.onError = (error, stack) { + _log.severe("PLATFORM_ERROR", error, stack); AuthProxyService.logError("PLATFORM_ERROR: $error\n$stack"); return true; }; @@ -29,7 +39,7 @@ void main() async { try { await dotenv.load(fileName: ".env"); } catch (e) { - debugPrint("Warning: .env file not found."); + _log.warning("Warning: .env file not found."); } // Initialize Descope @@ -40,13 +50,15 @@ void main() async { try { await Descope.sessionManager.loadSession(); } catch (e) { - debugPrint("Failed to load session: $e"); + _log.warning("Failed to load session: $e"); } runApp(const ProviderScope(child: BaronSSOApp())); } // Router Configuration +final _routerLogger = Logger('Router'); + final _router = GoRouter( initialLocation: '/', debugLogDiagnostics: true, // Enable diagnostic logs @@ -54,7 +66,7 @@ final _router = GoRouter( GoRoute( path: '/', builder: (context, state) { - debugPrint("[Router] Navigating to root (LoginScreen)"); + _routerLogger.info("Navigating to root (LoginScreen)"); return const LoginScreen(); } ), @@ -62,14 +74,14 @@ final _router = GoRouter( path: '/verify/:token', builder: (context, state) { final token = state.pathParameters['token']; - debugPrint("[Router] Navigating to /verify with token: $token"); + _routerLogger.info("Navigating to /verify with token: $token"); return LoginScreen(verificationToken: token); }, ), GoRoute( path: '/dashboard', builder: (context, state) { - debugPrint("[Router] Navigating to /dashboard"); + _routerLogger.info("Navigating to /dashboard"); return const DashboardScreen(); }, ), @@ -80,14 +92,14 @@ final _router = GoRouter( final path = state.uri.path; final isLoggingIn = path == '/' || path.startsWith('/verify/'); - debugPrint("[Router] Redirect check - Path: $path, IsLoggedIn: $isLoggedIn"); + _routerLogger.fine("Redirect check - Path: $path, IsLoggedIn: $isLoggedIn"); if (!isLoggedIn && !isLoggingIn) { - debugPrint("[Router] Not logged in, redirecting to /"); + _routerLogger.info("Not logged in, redirecting to /"); return '/'; } if (isLoggedIn && path == '/') { - debugPrint("[Router] Logged in, redirecting to /dashboard"); + _routerLogger.info("Logged in, redirecting to /dashboard"); return '/dashboard'; } diff --git a/frontend/nginx.conf b/frontend/nginx.conf index c9ef4dd9..8d160cb8 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -1,5 +1,29 @@ +# Map ISO8601 time to "YYYY-MM-DD HH:mm:ss" format +map $time_iso8601 $time_custom { + "~^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})" "$1-$2-$3 $4:$5:$6"; +} + +# Custom JSON Log Format matching Go slog +log_format json_combined escape=json + '{' + '"time":"$time_custom",' + '"level":"INFO",' + '"msg":"http_access",' + '"svc":"baron-frontend",' + '"status":$status,' + '"method":"$request_method",' + '"path":"$request_uri",' + '"latency":"${request_time}s",' + '"ip":"$remote_addr",' + '"forwarded_for":"$http_x_forwarded_for",' + '"user_agent":"$http_user_agent"' + '}'; + server { listen 5000; + include /etc/nginx/mime.types; + + access_log /var/log/nginx/access.log json_combined; # Backend API Proxy location /api { diff --git a/frontend/pubspec.yaml b/frontend/pubspec.yaml index 3bdafc10..5dedbd77 100644 --- a/frontend/pubspec.yaml +++ b/frontend/pubspec.yaml @@ -41,6 +41,8 @@ dependencies: google_fonts: ^6.3.3 flutter_dotenv: ^5.1.0 url_launcher: ^6.3.2 + logging: ^1.2.0 + logger: ^2.0.0 dev_dependencies: flutter_test: