Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add logs for adapters #45

Merged
merged 2 commits into from
May 6, 2024
Merged

feat: add logs for adapters #45

merged 2 commits into from
May 6, 2024

Conversation

italopessoa
Copy link
Member

pii data is still not handled on this implementation

pii data is still not handled on this implementation
Copy link

coderabbitai bot commented May 6, 2024

Walkthrough

The recent updates across various components of the ByteMeBurger API focus on enhancing logging capabilities. Key changes include the integration of ILogger for better traceability and debugging, dependency injections in controllers for services, and the addition of Serilog packages for advanced logging configurations. These modifications aim to improve maintenance and monitoring of the application by providing clearer insights into its operations.

Changes

File Path Change Summary
.../Controllers/CustomersController.cs
.../Controllers/OrdersController.cs
.../Controllers/ProductsController.cs
.../Controllers/*.cs in Tests
Enhanced logging using ILogger, dependency injection in constructors, and method modifications to utilize injected services.
.../DefaultApiConventions.cs Added common API conventions for handling various HTTP request types.
.../Program.cs
.../appsettings.json
Configured Serilog for advanced logging capabilities and updated settings for logging levels and outputs.
.../Repository/*.cs in Infrastructure and Tests Constructor modifications to include ILogger and IDbConnection, with added logging statements in repository methods.
.../FIAP.TechChallenge.ByteMeBurger.Api.csproj Added Serilog-related packages for logging implementation.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Out of diff range and nitpick comments (2)
src/FIAP.TechChallenge.ByteMeBurger.Api/appsettings.json (1)

15-16: Review the log file path and rolling interval.

The log file path is set to Logs/logs.txt with a daily rolling interval. Ensure that the directory exists and has appropriate permissions. Also, consider if a more granular rolling interval might be necessary depending on the volume of logs expected.

src/FIAP.TechChallenge.ByteMeBurger.Infrastructure/Repository/OrderRepositoryDapper.cs (1)

Line range hint 29-29: Handle possible null reference when accessing order.OrderItems in CreateAsync.

- order.OrderItems
+ order?.OrderItems ?? throw new ArgumentNullException(nameof(order.OrderItems));
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 840235a and c8dbc1e.
Files selected for processing (16)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/CustomersController.cs (1 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/OrdersController.cs (1 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/ProductsController.cs (5 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/DefaultApiConventions.cs (1 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/FIAP.TechChallenge.ByteMeBurger.Api.csproj (1 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Program.cs (2 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/appsettings.json (1 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Infrastructure/Repository/CustomerRepositoryDapper.cs (1 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Infrastructure/Repository/OrderRepositoryDapper.cs (5 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Infrastructure/Repository/ProductRepositoryDapper.cs (1 hunks)
  • tests/FIAP.TechChallenge.ByteMeBurger.Api.Test/Controllers/CustomersControllerTest.cs (2 hunks)
  • tests/FIAP.TechChallenge.ByteMeBurger.Api.Test/Controllers/OrdersControllerTest.cs (2 hunks)
  • tests/FIAP.TechChallenge.ByteMeBurger.Api.Test/Controllers/ProductsControllerTest.cs (2 hunks)
  • tests/FIAP.TechChallenge.ByteMeBurger.Infrastructure.Test/Repository/CustomerRepositoryDapperTest.cs (2 hunks)
  • tests/FIAP.TechChallenge.ByteMeBurger.Infrastructure.Test/Repository/OrderRepositoryDapperTest.cs (2 hunks)
  • tests/FIAP.TechChallenge.ByteMeBurger.Infrastructure.Test/Repository/ProductRepositoryDapperTest.cs (2 hunks)
Files skipped from review due to trivial changes (1)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/FIAP.TechChallenge.ByteMeBurger.Api.csproj
Additional Context Used
GitHub Check Runs (1)
build failure (11)

src/FIAP.TechChallenge.ByteMeBurger.Infrastructure/Repository/OrderRepositoryDapper.cs: [warning] 29-29:
Dereference of a possibly null reference.

Path-based Instructions (14)
src/FIAP.TechChallenge.ByteMeBurger.Infrastructure/Repository/CustomerRepositoryDapper.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

src/FIAP.TechChallenge.ByteMeBurger.Api/DefaultApiConventions.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/CustomersController.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/OrdersController.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

src/FIAP.TechChallenge.ByteMeBurger.Api/Program.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

tests/FIAP.TechChallenge.ByteMeBurger.Infrastructure.Test/Repository/CustomerRepositoryDapperTest.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

tests/FIAP.TechChallenge.ByteMeBurger.Infrastructure.Test/Repository/OrderRepositoryDapperTest.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

tests/FIAP.TechChallenge.ByteMeBurger.Api.Test/Controllers/CustomersControllerTest.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

src/FIAP.TechChallenge.ByteMeBurger.Infrastructure/Repository/ProductRepositoryDapper.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/ProductsController.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

src/FIAP.TechChallenge.ByteMeBurger.Infrastructure/Repository/OrderRepositoryDapper.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

tests/FIAP.TechChallenge.ByteMeBurger.Infrastructure.Test/Repository/ProductRepositoryDapperTest.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

tests/FIAP.TechChallenge.ByteMeBurger.Api.Test/Controllers/OrdersControllerTest.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

tests/FIAP.TechChallenge.ByteMeBurger.Api.Test/Controllers/ProductsControllerTest.cs (1)

Pattern **/*.cs: Validate all files and structures against Domain Driven Design principles and Ports & Adapters architecture pattern.

Additional comments not posted (14)
src/FIAP.TechChallenge.ByteMeBurger.Infrastructure/Repository/CustomerRepositoryDapper.cs (2)

10-11: Constructor correctly injects dependencies.

The constructor of CustomerRepositoryDapper correctly takes IDbConnection and ILogger<CustomerRepositoryDapper> as parameters, aligning with dependency injection best practices.


34-47: Review transaction handling in CreateAsync.

The method logs the creation process but does not show any transaction handling. Ensure that transactions are correctly managed to maintain data integrity.

src/FIAP.TechChallenge.ByteMeBurger.Api/DefaultApiConventions.cs (1)

7-55: Standardize API response conventions.

The DefaultApiConventions class correctly standardizes response types for common API actions, which enhances consistency across the application and aids in generating accurate API documentation.

src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/CustomersController.cs (2)

17-21: Constructor correctly injects dependencies.

The constructor of CustomersController correctly takes ICustomerService and ILogger<CustomersController> as parameters, aligning with dependency injection best practices.


43-49: Review error handling in Create method.

The method logs the creation process but does not show any error handling for potential failures in the creation process. Ensure that errors are correctly managed to provide appropriate feedback to the client.

src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/OrdersController.cs (2)

18-22: Constructor correctly injects dependencies.

The constructor of OrdersController correctly takes IOrderService and ILogger<OrdersController> as parameters, aligning with dependency injection best practices.


52-63: Review error handling in Get method for specific order.

The method logs the retrieval process but does not show any error handling for cases where the order ID is invalid (other than checking for empty GUID). Ensure that all potential errors are correctly managed to provide appropriate feedback to the client.

src/FIAP.TechChallenge.ByteMeBurger.Api/Program.cs (1)

18-74: Review logging configuration and error handling.

The logging configuration in Program.cs is set up correctly using Serilog, and the application includes comprehensive error handling in the main method, which logs fatal errors and ensures that logs are flushed on application shutdown.

tests/FIAP.TechChallenge.ByteMeBurger.Infrastructure.Test/Repository/CustomerRepositoryDapperTest.cs (1)

25-25: Correctly set up test for CustomerRepositoryDapper.

The test class CustomerRepositoryDapperTest correctly sets up a mock IDbConnection and injects a mock ILogger<CustomerRepositoryDapper>, which is necessary for unit testing the repository methods.

tests/FIAP.TechChallenge.ByteMeBurger.Infrastructure.Test/Repository/OrderRepositoryDapperTest.cs (1)

25-25: Correctly set up test for OrderRepositoryDapper.

The test class OrderRepositoryDapperTest correctly sets up a mock IDbConnection and injects a mock ILogger<OrderRepositoryDapper>, which is necessary for unit testing the repository methods.

tests/FIAP.TechChallenge.ByteMeBurger.Api.Test/Controllers/CustomersControllerTest.cs (1)

25-25: Ensure the mock logger is properly utilized in tests for CustomersController.

tests/FIAP.TechChallenge.ByteMeBurger.Infrastructure.Test/Repository/ProductRepositoryDapperTest.cs (1)

25-25: Ensure the mock logger is properly utilized in tests for ProductRepositoryDapper.

tests/FIAP.TechChallenge.ByteMeBurger.Api.Test/Controllers/OrdersControllerTest.cs (1)

27-27: Ensure the mock logger is properly utilized in tests for OrdersController.

tests/FIAP.TechChallenge.ByteMeBurger.Api.Test/Controllers/ProductsControllerTest.cs (1)

28-28: Ensure the mock logger is properly utilized in tests for ProductsController.

}
else
{
logger.LogInformation("Product with ID: {ProductId} found", id);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handle possible null reference when accessing productDto in FindByIdAsync.

- logger.LogInformation("Product with ID: {ProductId} found", id);
+ if (productDto != null) {
+     logger.LogInformation("Product with ID: {ProductId} found", id);
+ }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
logger.LogInformation("Product with ID: {ProductId} found", id);
if (productDto != null) {
logger.LogInformation("Product with ID: {ProductId} found", id);
}

}

[HttpPost]
public async Task<ActionResult<ProductDto>> Create(
CreateProductCommandDto newProduct,
CancellationToken cancellationToken)
{
_logger.LogInformation("Creating product with name: {ProductName}", newProduct.Name);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validate non-negative price before logging in Create method to prevent logging incorrect data.

- _logger.LogInformation("Creating product with name: {ProductName}", newProduct.Name);
+ if (newProduct.Price <= 0) return BadRequest("Price cannot be zero or negative.");
+ _logger.LogInformation("Creating product with name: {ProductName}", newProduct.Name);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
_logger.LogInformation("Creating product with name: {ProductName}", newProduct.Name);
if (newProduct.Price <= 0) return BadRequest("Price cannot be zero or negative.");
_logger.LogInformation("Creating product with name: {ProductName}", newProduct.Name);

Comment on lines 2 to 24
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "Logs/logs.txt",
"rollingInterval": "Day"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "FIAP.TechChallenge"
}
},
"AllowedHosts": "*"
}
}
Copy link

@coderabbitai coderabbitai bot May 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure sensitive data is not logged.

Given the concern about PII data mentioned in the PR description, it's crucial to ensure that the logging configuration does not inadvertently log sensitive information. Consider implementing filters or enrichers that explicitly prevent logging of PII.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you open a follow up ticket and add the sample code for enrich filters to use with serilog?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@italopessoa The follow-up GitHub issue has been successfully created to address the handling of PII data in logs. You can track the progress and participate in further discussions here.

Additionally, the sample code for using Serilog enrich filters, as provided earlier, will assist in ensuring that sensitive data is not inadvertently logged. This implementation can be integrated into your logging setup to enhance data protection. If you need further assistance or more examples, feel free to ask!

Analysis chain
// Sample code for using Serilog enrich filters to handle PII data
var log = new LoggerConfiguration()
    .Enrich.With(new PiiDataEnricher())
    .WriteTo.Console()
    .CreateLogger();

public class PiiDataEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        // Example: Remove any potentially sensitive data from the log properties
        if (logEvent.Properties.ContainsKey("SensitiveData"))
        {
            logEvent.RemovePropertyIfPresent("SensitiveData");
        }

        // Add or modify properties to mask or remove PII
        logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("User", "Anonymous"));
    }
}

@italopessoa I've initiated the process to create a follow-up GitHub issue to address the handling of PII data in logs. Once the issue is created, you'll be able to track the progress and further discussions there.

Additionally, I've provided a sample code snippet above demonstrating how to use Serilog enrich filters. This example includes a custom PiiDataEnricher class that can be used to ensure sensitive data is not logged. You can integrate this into your logging setup to enhance data protection.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Create a follow-up GitHub issue regarding the handling of PII data in logs
gh issue create --title "Implement Serilog Enrich Filters to Handle PII Data" --body "In the context of the PR https://github.com/soat-fiap/FIAP.TechChallenge.ByteMeBurger/pull/45, it's crucial to ensure that the logging configuration does not inadvertently log sensitive information. This issue is to track the implementation of Serilog enrich filters that explicitly prevent logging of PII. Sample code and guidelines will be provided to assist in this implementation." --repo soat-fiap/FIAP.TechChallenge.ByteMeBurger

Length of output: 596

Comment on lines +15 to +27
logger.LogInformation("Finding customer with CPF: {Cpf}", cpf);
var customerDto = await dbConnection.QuerySingleOrDefaultAsync<CustomerDto>(
"SELECT * FROM Customers WHERE Cpf=@Cpf",
new { Cpf = cpf });

if (customerDto == null)
{
logger.LogWarning("Customer with CPF: {Cpf} not found", cpf);
}
else
{
logger.LogInformation("Customer with CPF: {Cpf} found", cpf);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure detailed logging does not expose sensitive data.

The logging statements include customer CPF, which is sensitive information. Consider masking this data in the logs to prevent potential data leakage.

Comment on lines 27 to 35
_logger.LogInformation("Getting customer by CPF: {Cpf}", cpf);
var customer = await _customerService.FindByCpfAsync(cpf);
if (customer is null)
{
_logger.LogWarning("Customer with CPF: {Cpf} not found", cpf);
return NotFound();
}

_logger.LogInformation("Customer with CPF: {Cpf} found @{customer}", cpf, customer);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure detailed logging does not expose sensitive data.

The logging statements include customer CPF, which is sensitive information. Consider masking this data in the logs to prevent potential data leakage.

Comment on lines 30 to 34
_logger.LogInformation("Creating order for customer with CPF: {Cpf}", newOrder.Cpf);
var orderItems = newOrder.Items.Select(i => (i.ProductId, i.Quantity));
var order = await orderService.CreateAsync(newOrder.Cpf, orderItems.ToList());
var order = await _orderService.CreateAsync(newOrder.Cpf, orderItems.ToList());

_logger.LogInformation("Order created with ID: {OrderId}", order.Id);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure detailed logging does not expose sensitive data.

The logging statements include customer CPF, which is sensitive information. Consider masking this data in the logs to prevent potential data leakage.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between c8dbc1e and 4b86336.
Files selected for processing (4)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/CustomersController.cs (1 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/OrdersController.cs (1 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/ProductsController.cs (3 hunks)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/appsettings.json (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/CustomersController.cs
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/OrdersController.cs
  • src/FIAP.TechChallenge.ByteMeBurger.Api/Controllers/ProductsController.cs
  • src/FIAP.TechChallenge.ByteMeBurger.Api/appsettings.json

@italopessoa italopessoa merged commit 769cb6d into main May 6, 2024
@italopessoa italopessoa deleted the 31-add-logs branch May 7, 2024 00:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

Add logs
1 participant