Quick Start with ByteHide Logger
Prerequisites
Before you begin, make sure you have:
- A ByteHide account and project token
- .NET SDK installed (supports .NET Standard 2.0+, .NET Framework 4.7.2+, .NET 6+)
Quick Start Guide
- Install ByteHide Logger in your project
- Initialize the logger with your project token
- Start logging with simple API calls
- View logs in the ByteHide web panel
- Explore advanced features as needed
Step 1: Installation
Add the ByteHide Logger package to your project:
dotnet add package ByteHide.Logger
Step 2: Basic Setup
Initialize the logger in your application startup:
using Bytehide.Logger.Core;
using Bytehide.Logger.Common.Models;
class Program
{
static void Main(string[] args)
{
// Initialize the logger
Log.Initialize(new LogSettings
{
MinimumLevel = LogLevel.Info,
ConsoleEnabled = true,
Persist = true,
FilePath = "logs/app.log"
});
// Set your project token
Log.SetProjectToken("your-project-token-here");
// Your application code
RunApplication();
}
static void RunApplication()
{
Log.Info("Application started successfully!");
try
{
// Simulate some work
ProcessOrder("ORD-001", "CUST-123");
}
catch (Exception ex)
{
Log.Error("Application error occurred", ex);
}
finally
{
Log.Info("Application finished");
}
}
static void ProcessOrder(string orderId, string customerId)
{
Log.Info("Processing order", new {
OrderId = orderId,
CustomerId = customerId
});
// Simulate processing time
Thread.Sleep(1000);
Log.Info("Order processed successfully", new {
OrderId = orderId,
ProcessingTime = "1.2s"
});
}
}
Step 3: Basic Logging
Use the simple logging API throughout your application:
using Bytehide.Logger.Core;
public class UserService
{
public async Task<User> GetUserAsync(string userId)
{
Log.Debug($"Fetching user with ID: {userId}");
try
{
var user = await database.GetUserAsync(userId);
Log.Info("User retrieved successfully", new {
UserId = userId,
Username = user.Username
});
return user;
}
catch (UserNotFoundException ex)
{
Log.Warn($"User not found: {userId}");
throw;
}
catch (Exception ex)
{
Log.Error("Failed to retrieve user", ex);
throw;
}
}
public async Task CreateUserAsync(User user)
{
Log.Info("Creating new user", new {
Username = user.Username,
Email = user.Email
});
try
{
await database.CreateUserAsync(user);
Log.Info("User created successfully", new { UserId = user.Id });
}
catch (Exception ex)
{
Log.Error("Failed to create user", ex);
throw;
}
}
}
Step 4: Advanced Logging Features
Structured Logging with Context
// Add context to your logs
Log.WithContext("UserId", "12345")
.WithContext("SessionId", "sess-abc")
.Info("User performed action");
// Use tags for categorization
Log.WithTags("payment", "critical")
.Info("Payment processing started");
// Combine context and tags
Log.WithContext("OrderId", "ORD-001")
.WithContext("Amount", 99.99m)
.WithTags("payment", "success")
.Info("Payment completed");
User Identification
using Bytehide.Logger.Common.Models.Users;
// Identify the current user
Log.Identify(new AuthUser
{
Id = "user-123",
Email = "john.doe@company.com",
Name = "John Doe"
});
// All subsequent logs will include user information
Log.Info("User action performed");
Log.Warn("User attempted unauthorized action");
Correlation IDs
// Set correlation ID for request tracking
Log.SetCorrelationId(HttpContext.TraceIdentifier);
// All logs in this request will have the same correlation ID
Log.Info("Request started");
Log.Info("Processing data");
Log.Info("Request completed");
Step 5: Production Configuration
For production environments, use a more comprehensive configuration:
Log.Initialize(new LogSettings
{
// Log levels
MinimumLevel = LogLevel.Warn, // Only warnings and errors in production
// File logging
Persist = true,
FilePath = "logs/production.log",
RollingInterval = RollingInterval.Day,
FileSizeLimitBytes = 50 * 1024 * 1024, // 50 MB
// Security
MaskSensitiveData = new[] {
"password", "token", "secret", "key",
"credential", "connectionstring"
},
// Performance
DuplicateSuppressionWindow = TimeSpan.FromSeconds(10),
// Disable console in production
ConsoleEnabled = false
});
// Use environment variable for project token
var projectToken = Environment.GetEnvironmentVariable("BYTEHIDE_LOGS_TOKEN");
Log.SetProjectToken(projectToken);
Step 6: ASP.NET Core Integration
For web applications, integrate with ASP.NET Core:
// Program.cs
using Bytehide.Logger.Core;
using Bytehide.Logger.Common.Models;
var builder = WebApplication.CreateBuilder(args);
// Initialize ByteHide Logger
Log.Initialize(new LogSettings
{
MinimumLevel = LogLevel.Info,
ConsoleEnabled = builder.Environment.IsDevelopment(),
Persist = true,
FilePath = "logs/web-app.log",
RollingInterval = RollingInterval.Day
});
Log.SetProjectToken(builder.Configuration["ByteHideLogger:ProjectToken"]);
var app = builder.Build();
// Log application startup
Log.Info("Web application starting", new {
Environment = app.Environment.EnvironmentName,
Version = "1.0.0"
});
app.Run();
Step 7: View Your Logs
After your application runs, you can view logs in multiple places:
Console Output (Development)
[2024-01-15 10:30:15] [Info] Application started successfully!
[2024-01-15 10:30:15] [Info] Processing order { OrderId: "ORD-001", CustomerId: "CUST-123" }
[2024-01-15 10:30:16] [Info] Order processed successfully { OrderId: "ORD-001", ProcessingTime: "1.2s" }
Log Files
Check your configured log file path (e.g., logs/app.log
):
2024-01-15 10:30:15.123 [INFO] Application started successfully!
2024-01-15 10:30:15.456 [INFO] Processing order OrderId=ORD-001 CustomerId=CUST-123
2024-01-15 10:30:16.789 [INFO] Order processed successfully OrderId=ORD-001 ProcessingTime=1.2s
ByteHide Web Panel
- Log in to ByteHide Cloud
- Select your Logs project
- View real-time logs, search, filter, and analyze
Common Patterns
Error Handling
public async Task<ApiResponse> ProcessRequestAsync(Request request)
{
var correlationId = Guid.NewGuid().ToString();
Log.SetCorrelationId(correlationId);
try
{
Log.Info("Request received", new {
RequestId = request.Id,
Type = request.Type,
CorrelationId = correlationId
});
var result = await ProcessBusinessLogic(request);
Log.Info("Request processed successfully", new {
RequestId = request.Id,
ResultCount = result.Items.Count
});
return ApiResponse.Success(result);
}
catch (ValidationException ex)
{
Log.Warn("Request validation failed", new {
RequestId = request.Id,
ValidationErrors = ex.Errors
});
return ApiResponse.BadRequest(ex.Message);
}
catch (Exception ex)
{
Log.Error("Request processing failed", ex);
return ApiResponse.InternalServerError();
}
finally
{
Log.ClearCorrelationId();
}
}
Performance Monitoring
public async Task<List<Product>> GetProductsAsync(int categoryId)
{
var stopwatch = Stopwatch.StartNew();
try
{
var products = await repository.GetProductsByCategoryAsync(categoryId);
stopwatch.Stop();
Log.Info("Products retrieved", new {
CategoryId = categoryId,
ProductCount = products.Count,
ElapsedMs = stopwatch.ElapsedMilliseconds
});
return products;
}
catch (Exception ex)
{
stopwatch.Stop();
Log.Error("Failed to retrieve products", ex, new {
CategoryId = categoryId,
ElapsedMs = stopwatch.ElapsedMilliseconds
});
throw;
}
}
Next Steps
Now that you have basic logging working: