一键导入
logging
Comprehensive logging standards for C# applications including structured logging, log levels, message formatting, and compliance guidelines
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Comprehensive logging standards for C# applications including structured logging, log levels, message formatting, and compliance guidelines
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
| name | logging |
| description | Comprehensive logging standards for C# applications including structured logging, log levels, message formatting, and compliance guidelines |
| version | 1.0.0 |
| author | BlackFULLness Platform Team |
| created | "2026-01-26T00:00:00.000Z" |
| updated | "2026-01-26T00:00:00.000Z" |
| tags | ["logging","csharp","structured-logging","observability","debugging"] |
| applies_to | ["**/*.cs","Services/**/*","Controllers/**/*","Api/**/*"] |
Comprehensive logging guidelines for consistent, structured, and maintainable logging across C# applications with emphasis on mental wellness platform requirements.
REQUIRED: All log messages MUST follow this pattern:
[CLASS_NAME_OR_SERVICE]: MESSAGE
The prefix should be the actual class name or service name where the logging occurs, enclosed in square brackets.
_logger.LogInformation("[SystemNotificationService]: Notification {NotificationId} sent to user {UserId}",
notificationId, userId);
_logger.LogInformation("[ActivityController.Store]: Activity saved to database - ActivityId: {ActivityId}",
activity.Id);
_logger.LogInformation("[ContentService]: Retrieved {Count} published meditations for institution {InstitutionId}",
count, institutionId);
_logger.LogWarning("[DeviceTokenService]: User {UserId} has no registered device tokens", userId);
_logger.LogWarning("[AnalyticsService]: Failed to queue event - {EventType}: {EventName} for UserId: {UserId}",
eventType, eventName, userId);
_logger.LogWarning("[BadgeEvaluationService]: Badge definition {BadgeId} not found during evaluation", badgeId);
_logger.LogError(ex, "[BadgeService]: Failed to award badge {BadgeId} to user {UserId}", badgeId, userId);
_logger.LogError(ex, "[NotificationService]: Failed to send notification {NotificationId}", notificationId);
_logger.LogError(ex, "[ActivityController.Store]: Failed to track activity analytics for user {UserId}", userId);
_logger.LogDebug("[CachedContentService]: Cache hit for content type {ContentType}", contentType);
_logger.LogDebug("[AnalyticsService]: Track event sent - Event: {EventName}, UserId: {UserId}, SessionId: {SessionId}",
eventName, userId, sessionId);
_logger.LogDebug("[ActivityController.Store]: MapEventToActivityType result - Event: {Event}, ContentType: {ContentType}, MappedActivityType: {ActivityType}",
activity.Event, activity.ContentType, activityType ?? "NULL");
✅ DO THIS - Structured logging with named parameters:
_logger.LogInformation("[NotificationService]: Notification {NotificationId} sent to user {UserId} at {Timestamp}",
notificationId, userId, DateTime.UtcNow);
❌ AVOID THIS - String interpolation or concatenation:
// Bad - loses structured logging benefits
_logger.LogInformation($"[NotificationService]: Notification {notificationId} sent to user {userId}");
Always include key identifiers for troubleshooting:
UserIdNotificationIdActivityIdBadgeIdContentIdSessionIdInstitutionId_logger.LogInformation("[BadgeService]: Badge {BadgeId} awarded to user {UserId} - TotalPoints: {Points}",
badgeId, userId, totalPoints);
Always use exception-first format:
// Correct - exception as first parameter
_logger.LogError(ex, "[ServiceName]: Error message with {ContextParam}", contextValue);
// Incorrect - exception in message
_logger.LogError($"[ServiceName]: Error occurred: {ex.Message}");
_logger.LogDebug("[UserActivityTrackingService]: Processing activity event - ActivityType: {ActivityType}, EntityId: {EntityId}",
activityType, entityId);
_logger.LogInformation("[AnalyticsService]: Initialized with Segment integration (write key configured)");
_logger.LogWarning("[ActivityController.Store]: {ErrorMessage}", errorMessage);
_logger.LogError(ex, "[AnalyticsService]: Failed to send analytics event {EventName} for user {UserId}",
eventName, userId);
_logger.LogCritical(ex, "[DatabaseService]: Unable to establish database connection after {RetryAttempts} attempts",
retryAttempts);
_logger.LogInformation("[ActivityController.Store]: Received activity - Event: {Event}, ContentType: {ContentType}, SessionId: {SessionId}",
data.Event, data.ContentType, data.SessionId);
_logger.LogWarning("[ActivityController.Store]: {ErrorMessage}", errorMessage);
_logger.LogInformation("[BadgeService]: Evaluating badges for user {UserId} - ActivityType: {ActivityType}",
userId, activityType);
_logger.LogError(ex, "[NotificationService]: Failed to process notification for user {UserId}", userId);
_logger.LogInformation("[NotificationSchedulingJobService]: Starting scheduled notification job");
_logger.LogWarning("[NotificationSchedulingJobService]: No notifications scheduled for processing");
_logger.LogDebug("[AnalyticsService]: Added sessionId {SessionId} to Segment context for user {UserId}",
sessionId, userId);
_logger.LogInformation("[AnalyticsService]: {EventType}: {EventName} - UserId: {UserId}, Properties: {Properties}",
eventType, eventName, userId, FormatProperties(properties));
// Bad - not specific enough
_logger.LogInformation("[Service]: Operation completed");
// Good - identifies exact service
_logger.LogInformation("[BadgeEvaluationService]: Badge evaluation completed for user {UserId}", userId);
// Bad - uses technology name instead of class name
_logger.LogDebug("SEGMENT Track: {eventName}");
// Good - uses actual class name
_logger.LogDebug("[AnalyticsService]: Track event sent - Event: {EventName}", eventName);
// Bad - logs sensitive information
_logger.LogInformation("[AuthService]: User logged in - Password: {Password}", password);
// Good - logs only non-sensitive identifiers
_logger.LogInformation("[AuthService]: User {UserId} logged in successfully", userId);
// Bad - loses structured logging
_logger.LogInformation($"[Service]: User {userId} performed action");
// Good - uses structured logging
_logger.LogInformation("[Service]: User {UserId} performed action", userId);
// Bad - can flood logs
foreach (var item in largeCollection)
{
_logger.LogDebug("[Service]: Processing item {ItemId}", item.Id);
}
// Good - log summary instead
_logger.LogInformation("[Service]: Processing {Count} items", largeCollection.Count);
// Log only errors or specific cases
// Bad - vague
_logger.LogError("[Service]: Error occurred");
// Good - specific and actionable
_logger.LogError(ex, "[NotificationService]: Failed to send push notification to device {DeviceToken} - User: {UserId}",
deviceToken, userId);
// Preferred
_logger.LogInformation("[Service]: Processing request");
_logger.LogInformation("[Service]: Request processed successfully");
// Not preferred
_logger.LogInformation("[Service]: Will process request");
_logger.LogWarning("[CachedContentService]: Cache miss for content type {ContentType} - InstitutionId: {InstitutionId}",
contentType, institutionId);
if (_logger.IsEnabled(LogLevel.Debug))
{
var detailedInfo = ExpensiveSerializationMethod(data);
_logger.LogDebug("[Service]: Detailed state - {DetailedInfo}", detailedInfo);
}
Only log at Information level or higher in performance-critical code. Use Debug level sparingly.
When writing unit tests, verify logging behavior:
_mockLogger.Verify(
x => x.Log(
LogLevel.Information,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((o, t) => o.ToString().Contains("[BadgeService]")),
null,
It.IsAny<Func<It.IsAnyType, Exception, string>>()),
Times.Once);
| Scenario | Log Level | Include |
|---|---|---|
| Successful operation | Information | Entity IDs, key parameters |
| Operation started | Debug | Context parameters |
| Unexpected but handled | Warning | What happened, how it was handled |
| Operation failed | Error | Exception, entity IDs, context |
| System critical failure | Critical | Exception, impact scope |
| Development debugging | Debug | Detailed state information |
// Good - logs hashed user identifier
_logger.LogDebug("[AnalyticsService]: Using hashed user ID for Segment");
// Bad - would log sensitive data
// _logger.LogDebug("[AnalyticsService]: User email: {Email}", userEmail);
Remember: Consistent, structured logging is essential for troubleshooting production issues, monitoring application health, and maintaining a high-quality codebase. Follow these standards religiously to ensure logs are useful and actionable.