0

I'm trying to get create an AuditLog for my moderated content and would like to add the Exception Message sent by the Azure Content Moderation API to the log. Can anyone assist me with regards to saving this to a variable?

To give you context to how it will work:

if (isProfanity)
                {
                    
                    throw new RemoteException("The username contains profanity. Please pick a different one.",
                        "The username contains profanity and has been denied.",
                        RemoteExceptionType.ProfileUsernameProfanityException);
                }
                else if (warning)
                {
                    var log = new ProfanityAuditLog
                    {
                        Username = text,
                        DetectedLanguage = detectedLanguage.DetectedLanguageProperty,
                        IsProfanity = isProfanity,
                        ThresholdCategory1 = _options.ThresholdCategory1,
                        ThresholdCategory2 = _options.ThresholdCategory2,
                        ThresholdCategory3 = _options.ThresholdCategory3,
                        //ExceptionMessage = exception
                    };
                    _profanityAuditRepo.AddLogAsync(log);
                    throw new RemoteException("The username might contain profanity.",
                        "The username might contain profanity and will have to be validated by support.",
                        RemoteExceptionType.ProfileUsernameProfanityWarningException);
                }

If the word is profanity the remote exception should be thrown and the word should be considered profanity, if the word falls between the ratio of 0.5 & 0.7 the word should be categorized as a warning and be added to the AuditLog for user validation and a emote exception should be thrown to tell the user. The issue is the Exception Message I am referring to in the log needs to be the exception I receive from Azure, this is in case the issue is related to Azure and not the word e.g. API service is down.

This is what I got from some forums and Googling but it's not exactly what I am looking for.

 string exceptionMessage = screen?.Classification.ReviewRecommended? "Azure review recommended": "Custom warning message"
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Spottie97
  • 3
  • 2

1 Answers1

0

You are using a conditional expression to generate the exceptionMessage. This won't directly capture the exception thrown by the Azure Content Moderation API.

  • Catch the exception thrown by the API, extract the error message, and then include it in your log.

Here, I create a sample Data model in console App to capture exception messages for moderated content using the Azure Content Moderation API.

  • ProfanityAuditLog, this will hold the information you want to log.
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.ContentModerator;
using Microsoft.Azure.CognitiveServices.ContentModerator.Models;

namespace ContentModerationApp
{
    internal class Program
    {
        private static async Task Main(string[] args)
        {
            Console.WriteLine("Enter a username or text to check for profanity:");
            string userInput = Console.ReadLine();

            try
            {
                await CheckContentAsync(userInput);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
                SaveToAuditLog(userInput, ex.Message);
            }
        }

        public static async Task CheckContentAsync(string text)
        {
            // Replace with your Azure Content Moderator API key and endpoint
            string apiKey = "************";
            string endpoint = "https://******.cognitiveservices.azure.com/";

            var client = new ContentModeratorClient(new ApiKeyServiceClientCredentials(apiKey)) { Endpoint = endpoint };

            try
            {
                var screen = await client.TextModeration.ScreenTextAsync("text/plain", new MemoryStream(Encoding.UTF8.GetBytes(text)));

                string exceptionMessage = "No exception occurred"; // Initialize a default value

                if (screen != null && screen.Classification != null && screen.Classification.ReviewRecommended == true)
                {
                    if (screen.Classification.Category1?.Score > 0.7)
                    {
                        exceptionMessage = "The username might contain profanity and will have to be validated by support.";
                        throw new Exception(exceptionMessage);
                    }
                    else if (screen.Classification.Category1?.Score > 0.5)
                    {
                        // Handle the case where user input falls between 0.5 and 0.7 (custom logic)
                    }
                }

                // ... (other code)
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred during content moderation: {ex.Message}");
                throw;
            }
        }

        public static void SaveToAuditLog(string userInput, string exceptionMessage)
        {
            string logFilePath = "C:\\Users\\v-chikkams\\Downloads\\test.txt";

            using (StreamWriter writer = File.AppendText(logFilePath))
            {
                writer.WriteLine($"User Input: {userInput}");
                writer.WriteLine($"Exception Message: {exceptionMessage}");
                writer.WriteLine($"Timestamp: {DateTime.Now}");
                writer.WriteLine(new string('-', 40));
            }

            Console.WriteLine("Saved to audit log.");
        }
    }
}
  • The above application will reproduce the content moderation and log based on given username or text to be checked for profanity.

enter image description here

when a RemoteException is caught, it will save the relevant information to the audit log file. Then you can deploy to app service.

Suresh Chikkam
  • 623
  • 2
  • 2
  • 6