1
0
forked from baron/baron-sso

로그 포맷 통일, slog 적용

This commit is contained in:
2026-01-15 14:16:34 +09:00
parent 2aff11bc5d
commit 5dd2c94555
9 changed files with 286 additions and 32 deletions

View File

@@ -99,19 +99,28 @@ class AuthProxyService {
}
}
static Future<void> logError(String message) async {
static Future<void> sendLog(String level, String message, {Map<String, dynamic>? 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<void> logError(String message, {dynamic error, StackTrace? stackTrace}) async {
final data = <String, dynamic>{};
if (error != null) data['error'] = error.toString();
if (stackTrace != null) data['stack'] = stackTrace.toString();
await sendLog('ERROR', message, data: data);
}
}

View File

@@ -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(),
},
);
}
}
}

View File

@@ -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';
}

View File

@@ -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 {

View File

@@ -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: