diff --git a/content/arabic/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/arabic/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..9e184d23 --- /dev/null +++ b/content/arabic/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,182 @@ +--- +date: '2026-03-28' +description: تعلم كيفية تنفيذ مسجل مخصص بلغة C# في GroupDocs.Redaction لـ .NET، مما + يتيح تسجيل مخصص مفصل في .NET وتسهيل إعداد تقارير الامتثال. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: تنفيذ مسجل مخصص C# في GroupDocs.Redaction لـ .NET +type: docs +url: /ar/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# تنفيذ مسجل مخصص c# في GroupDocs.Redaction لـ .NET + +إدارة عمليات إخفاء المستندات بكفاءة أمر حاسم، خاصةً عند التعامل مع معلومات حساسة. في هذا الدليل ستتعلم **كيفية تنفيذ مسجل مخصص c#** مع GroupDocs.Redaction لـ .NET، مما يمنحك سيطرة كاملة على التسجيل، ومعالجة الأخطاء، وسجلات التدقيق. + +## إجابات سريعة +- **ماذا يفعل مسجل مخصص c#؟** يلتقط الأخطاء والتحذيرات والرسائل المعلوماتية أثناء الإخفاء. +- **أي مكتبة توفر واجهة ILogger؟** GroupDocs.Redaction لـ .NET. +- **هل يمكنني حفظ المستند المُخفى دون التحويل إلى نقطية؟** نعم – استخدم `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **هل أحتاج إلى ترخيص للاستخدام في الإنتاج؟** يلزم ترخيص كامل للإنتاج؛ يتوفر نسخة تجريبية للتقييم. +- **هل هذا النهج متوافق مع .NET Core / .NET 6+؟** بالتأكيد – نفس الـ API يعمل عبر .NET Framework و .NET Core/5/6. + +## ما هو مسجل مخصص c#؟ +مسجل مخصص **c#** هو فئة تقوم بتنفيذ واجهة `ILogger` التي توفرها GroupDocs.Redaction. يتيح لك توجيه رسائل السجل إلى أي مكان تحتاجه—الكونسول، الملف، قاعدة البيانات، أو أنظمة المراقبة الخارجية—مع توفير رؤية واضحة لسير عمل الإخفاء. + +## لماذا استخدام تسجيل مخصص .net مع GroupDocs.Redaction؟ +- **الامتثال والتدقيق:** السجلات التفصيلية تلبي المتطلبات التنظيمية. +- **رؤية الأخطاء:** `LogError` و `LogWarning` يقدمان لك رد فعل فوري على المشكلات. +- **مرونة التكامل:** تحويل السجلات إلى أطر تسجيل .NET الموجودة (Serilog، NLog، إلخ). + +## المتطلبات المسبقة +- **GroupDocs.Redaction لـ .NET** مثبت (انظر التثبيت أدناه). +- بيئة تطوير .NET (Visual Studio، VS Code، أو سطر الأوامر). +- معرفة أساسية بـ C# وإلمام بتدفقات الملفات. + +## التثبيت + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +ابحث عن **"GroupDocs.Redaction"** وقم بتثبيت أحدث نسخة. + +## الحصول على الترخيص +- **نسخة تجريبية مجانية:** اختبار الـ API بترخيص مؤقت. +- **ترخيص مؤقت:** الحصول على الوصول الكامل للميزات لفترة محدودة. +- **شراء:** الحصول على ترخيص دائم للنشر في بيئات الإنتاج. + +## دليل خطوة بخطوة + +### الخطوة 1: تعريف فئة مسجل مخصص (log warnings c#) + +إنشاء فئة تقوم بتنفيذ `ILogger`. ستقوم هذه الفئة بالتقاط الأخطاء والتحذيرات والرسائل المعلوماتية. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**شرح:** علم `HasErrors` يساعدك على اتخاذ قرار ما إذا كنت ستستمر في المعالجة. الطرق الثلاثة تتطابق مع مستويات السجل الثلاث التي ستحتاجها في معظم سيناريوهات الإخفاء. + +### الخطوة 2: إعداد مسارات الملفات وفتح المستند المصدر + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**لماذا هذا مهم:** استخدام طرق المساعدة يحافظ على نظافة الكود ويضمن وجود مجلد الإخراج قبل محاولة **حفظ المستند المُخفى**. + +### الخطوة 3: تطبيق الإخفاءات أثناء استخدام المسجل المخصص + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**شرح:** +1. يتم إنشاء كائن `Redactor` باستخدام `RedactorSettings(logger)`، مما يربط `CustomLogger` الخاص بك. +2. بعد تطبيق الإخفاء، يتحقق الكود من `logger.HasErrors`. إذا لم تحدث أخطاء، يتم حفظ المستند—مما يوضح منطق **حفظ المستند المُخفى** دون التحويل إلى نقطية. + +### المشكلات الشائعة وإصلاح الأخطاء +- **غياب مخرجات السجل:** تأكد من أن كل طريقة `Log*` تم تجاوزها بشكل صحيح. +- **استثناءات الوصول إلى الملفات:** تأكد من أن التطبيق يمتلك صلاحيات القراءة/الكتابة لكل من مسارات المصدر والإخراج. +- **المسجل غير موصول:** معامل `RedactorSettings(logger)` أساسي؛ إهماله يعطل التسجيل المخصص. + +## التطبيقات العملية +1. **تقارير الامتثال:** تصدير سجلات السجل إلى CSV أو قاعدة بيانات لسجلات التدقيق. +2. **تتبع الأخطاء:** تحديد الملفات المشكلة بسرعة عبر فحص مخرجات `LogError`. +3. **أتمتة سير العمل:** تشغيل عمليات لاحقة (مثل إبلاغ مسؤول الامتثال) عند استدعاء `LogWarning`. + +## اعتبارات الأداء +- **تخلص من التدفقات بسرعة** لتحرير الذاكرة، خاصةً عند معالجة دفعات كبيرة. +- **راقب وحدة المعالجة المركزية والذاكرة** أثناء الإخفاءات الضخمة؛ فكر في معالجة المستندات بشكل متوازي مع مزامنة دقيقة للمسجل. +- **ابقَ محدثًا:** الإصدارات الأحدث من GroupDocs.Redaction غالبًا ما تتضمن تحسينات في الأداء وإضافات لسجلات إضافية. + +## الخلاصة + +من خلال تنفيذ **مسجل مخصص c#**، تحصل على رؤية دقيقة لكل خطوة في خط أنابيب الإخفاء، مما يسهل الالتزام بمعايير الامتثال وتصحيح المشكلات. النهج المعروض هنا يعمل بسلاسة مع GroupDocs.Redaction لـ .NET ويمكن توسيعه للتكامل مع أي إطار تسجيل .NET تستخدمه بالفعل. + +--- + +## الأسئلة المتكررة + +**س: ما هو هدف التسجيل المخصص مع GroupDocs.Redaction؟** +ج: يساعد التسجيل المخصص في تتبع وإدارة الإخفاءات للامتثال، وتتبع الأخطاء، وتحسين سير العمل. + +**س: كيف أتعامل مع الأخطاء باستخدام مسجل مخصص؟** +ج: نفّذ `LogError` في فئة `CustomLogger` الخاصة بك؛ علم `HasErrors` يتيح لك إيقاف المعالجة إذا لزم الأمر. + +**س: هل يمكن دمج التسجيل المخصص مع أنظمة أخرى؟** +ج: نعم، يمكنك توجيه رسائل السجل إلى أنظمة CRM أو ERP أو أدوات المراقبة المركزية عن طريق توسيع طرق المسجل. + +**س: ما هي بعض المشكلات الشائعة عند تنفيذ التسجيل المخصص؟** +ج: تنفيذ طرق غير صحيح، فقدان `RedactorSettings(logger)`، ومشكلات صلاحيات الملفات هي الأكثر شيوعًا. + +**س: كيف يحسن التسجيل المخصص سير عمل إخفاء المستندات؟** +ج: السجلات التفصيلية توفر رؤية في الوقت الحقيقي، تبسط استكشاف الأخطاء، وتلبي متطلبات التدقيق. + +## الموارد + +- **الوثائق:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **مرجع API:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **تحميل:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**آخر تحديث:** 2026-03-28 +**تم الاختبار مع:** GroupDocs.Redaction 23.11 لـ .NET +**المؤلف:** GroupDocs \ No newline at end of file diff --git a/content/chinese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/chinese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..7a6674ea --- /dev/null +++ b/content/chinese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,184 @@ +--- +date: '2026-03-28' +description: 了解如何在 GroupDocs.Redaction for .NET 中实现自定义 C# 日志记录器,以实现详细的自定义日志记录并更轻松地进行合规报告。 +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: 在 GroupDocs.Redaction for .NET 中实现自定义日志记录器(C#) +type: docs +url: /zh/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# 在 GroupDocs.Redaction for .NET 中实现自定义日志记录器 C# + +管理文档脱敏效率至关重要,尤其是在处理敏感信息时。在本指南中,您将学习 **如何在 GroupDocs.Redaction for .NET 中实现自定义日志记录器 C#**,从而全面控制日志记录、错误处理和审计跟踪。 + +## 快速答案 +- **自定义日志记录器 C# 的作用是什么?** 它在脱敏过程中捕获错误、警告和信息性消息。 +- **哪个库提供 ILogger 接口?** GroupDocs.Redaction for .NET。 +- **我可以在不进行光栅化的情况下保存脱敏文档吗?** 可以——使用 `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`。 +- **生产环境使用是否需要许可证?** 生产环境需要完整许可证;可使用试用版进行评估。 +- **此方法是否兼容 .NET Core / .NET 6+?** 完全兼容——相同的 API 在 .NET Framework 和 .NET Core/5/6 上均可使用。 + +## 什么是自定义日志记录器 C#? +**自定义日志记录器 C#** 是一个实现 GroupDocs.Redaction 提供的 `ILogger` 接口的类。它允许您将日志消息路由到任意位置——控制台、文件、数据库或外部监控系统——并让您清晰地了解脱敏工作流。 + +## 为什么在 GroupDocs.Redaction 中使用自定义日志记录 .NET? +- **合规与审计:** 详细日志满足监管要求。 +- **错误可见性:** `LogError` 和 `LogWarning` 为您提供即时的错误反馈。 +- **集成灵活性:** 将日志转发到现有的 .NET 日志框架(Serilog、NLog 等)。 + +## 先决条件 +- **已安装 GroupDocs.Redaction for .NET**(请参见下文的安装步骤)。 +- 具备 .NET 开发环境(Visual Studio、VS Code 或 CLI)。 +- 基本的 C# 知识并熟悉文件流。 + +## 安装 + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet 包管理器 UI** +搜索 **"GroupDocs.Redaction"** 并安装最新版本。 + +## 许可证获取 +- **免费试用:** 使用临时许可证测试 API。 +- **临时许可证:** 在有限期间内获取全部功能。 +- **购买:** 获得用于生产部署的永久许可证。 + +## 分步指南 + +### 步骤 1:定义自定义日志记录器类(记录警告 C#) + +创建一个实现 `ILogger` 的类。该类将捕获错误、警告和信息性消息。 + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**说明:** `HasErrors` 标志帮助您决定是否继续处理。三个方法对应大多数脱敏场景中需要的三个日志级别。 + +### 步骤 2:准备文件路径并打开源文档 + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**为何重要:** 使用实用方法保持代码整洁,并确保在尝试 **保存脱敏文档** 之前输出文件夹已存在。 + +### 步骤 3:在使用自定义日志记录器的同时应用脱敏 + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**说明:** +1. 使用 `RedactorSettings(logger)` 实例化 `Redactor`,将您的 `CustomLogger` 关联进去。 +2. 在应用脱敏后,代码检查 `logger.HasErrors`。如果没有错误发生,则保存文档——演示了在不进行光栅化的情况下 **保存脱敏文档** 的逻辑。 + +## 常见陷阱与故障排除 + +- **日志输出缺失:** 确认每个 `Log*` 方法已正确重写。 +- **文件访问异常:** 确保应用程序对源路径和输出路径都有读写权限。 +- **日志记录器未连接:** `RedactorSettings(logger)` 参数至关重要,省略它会导致自定义日志失效。 + +## 实际应用 + +1. **合规报告:** 将日志条目导出为 CSV 或数据库,以用于审计追踪。 +2. **错误追踪:** 通过扫描 `LogError` 输出快速定位有问题的文件。 +3. **工作流自动化:** 当调用 `LogWarning` 时触发下游流程(例如通知合规官)。 + +## 性能考虑 + +- **及时释放流** 以释放内存,尤其在处理大批量时。 +- **监控 CPU 与内存** 在批量脱敏期间;考虑在并行处理文档时谨慎同步日志记录器。 +- **保持更新:** 新版本的 GroupDocs.Redaction 通常包含性能优化和额外的日志钩子。 + +## 结论 + +通过实现 **自定义日志记录器 C#**,您可以细致了解脱敏流水线的每一步,从而更容易满足合规标准并调试问题。此方法可无缝配合 GroupDocs.Redaction for .NET 使用,并可扩展以集成您已有的任何 .NET 日志框架。 + +--- + +## 常见问题 + +**问:使用 GroupDocs.Redaction 的自定义日志记录的目的是什么?** +**答:** 自定义日志记录有助于跟踪和管理脱敏,以满足合规、错误追踪和工作流优化的需求。 + +**问:如何使用自定义日志记录器处理错误?** +**答:** 在您的 `CustomLogger` 类中实现 `LogError`;`HasErrors` 标志可在需要时中止处理。 + +**问:自定义日志记录可以与其他系统集成吗?** +**答:** 可以,通过扩展日志记录器方法将日志消息转发到 CRM、ERP 或集中监控工具。 + +**问:实现自定义日志记录时常见的陷阱有哪些?** +**答:** 方法实现错误、缺少 `RedactorSettings(logger)`、文件权限问题是最常见的。 + +**问:自定义日志记录如何改进文档脱敏工作流?** +**答:** 详细日志提供实时可视性,简化故障排除,并满足审计要求。 + +## 资源 + +- **文档:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API 参考:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **下载:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**最后更新:** 2026-03-28 +**测试环境:** GroupDocs.Redaction 23.11 for .NET +**作者:** GroupDocs \ No newline at end of file diff --git a/content/czech/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/czech/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..84b7d861 --- /dev/null +++ b/content/czech/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,182 @@ +--- +date: '2026-03-28' +description: Naučte se, jak v GroupDocs.Redaction pro .NET implementovat vlastní logger + v C#, který umožňuje podrobné vlastní protokolování a usnadňuje tvorbu zpráv o souladu. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Implementace vlastního loggeru v C# v GroupDocs.Redaction pro .NET +type: docs +url: /cs/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Implementujte vlastní logger c# v GroupDocs.Redaction pro .NET + +Efektivní správa redakcí dokumentů je kritická, zejména při práci s citlivými informacemi. V tomto průvodci se naučíte **jak implementovat vlastní logger c#** s GroupDocs.Redaction pro .NET, což vám poskytne plnou kontrolu nad logováním, zpracováním chyb a auditními stopami. + +## Rychlé odpovědi +- **Co dělá vlastní logger c#?** Zachycuje chyby, varování a informační zprávy během redakce. +- **Která knihovna poskytuje rozhraní ILogger?** GroupDocs.Redaction pro .NET. +- **Mohu uložit redigovaný dokument bez rasterizace?** Ano – použijte `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Potřebuji licenci pro produkční použití?** Pro produkci je vyžadována plná licence; k vyzkoušení je k dispozici zkušební verze. +- **Je tento přístup kompatibilní s .NET Core / .NET 6+?** Rozhodně – stejné API funguje napříč .NET Framework a .NET Core/5/6. + +## Co je vlastní logger c#? +Vlastní **logger c#** je třída, která implementuje rozhraní `ILogger` poskytované GroupDocs.Redaction. Umožňuje vám směrovat logovací zprávy kamkoli potřebujete – do konzole, souboru, databáze nebo externích monitorovacích systémů – a zároveň vám poskytuje přehled o workflow redakce. + +## Proč používat vlastní logování .net s GroupDocs.Redaction? +- **Soulad a audit:** Detailní logy splňují regulatorní požadavky. +- **Viditelnost chyb:** `LogError` a `LogWarning` vám poskytují okamžitou zpětnou vazbu o problémech. +- **Flexibilita integrace:** Přeposílejte logy do existujících .NET logovacích frameworků (Serilog, NLog, atd.). + +## Předpoklady +- **GroupDocs.Redaction pro .NET** nainstalován (viz instalace níže). +- Vývojové prostředí .NET (Visual Studio, VS Code nebo CLI). +- Základní znalost C# a zkušenost se souborovými proudy. + +## Instalace + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Vyhledejte **"GroupDocs.Redaction"** a nainstalujte nejnovější verzi. + +## Získání licence +- **Bezplatná zkušební verze:** Otestujte API s dočasnou licencí. +- **Dočasná licence:** Získejte plný přístup k funkcím na omezenou dobu. +- **Nákup:** Získejte trvalou licenci pro produkční nasazení. + +## Průvodce krok za krokem + +### Krok 1: Definujte vlastní třídu loggeru (log warnings c#) + +Vytvořte třídu, která implementuje `ILogger`. Tato třída bude zachycovat chyby, varování a informační zprávy. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Vysvětlení:** Příznak `HasErrors` vám pomáhá rozhodnout, zda pokračovat ve zpracování. Tři metody odpovídají třem úrovním logování, které budete potřebovat ve většině scénářů redakce. + +### Krok 2: Připravte cesty k souborům a otevřete zdrojový dokument + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Proč je to důležité:** Použití pomocných metod udržuje váš kód čistý a zajišťuje, že výstupní složka existuje, než se pokusíte **uložit redigovaný dokument**. + +### Krok 3: Aplikujte redakce při použití vlastního loggeru + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Vysvětlení:** +1. `Redactor` je vytvořen s `RedactorSettings(logger)`, čímž se propojí s vaším `CustomLogger`. +2. Po aplikaci redakce kód kontroluje `logger.HasErrors`. Pokud nedošlo k chybám, dokument se uloží – což demonstruje logiku **uložit redigovaný dokument** bez rasterizace. + +### Běžné úskalí a řešení problémů +- **Chybějící výstup logu:** Ověřte, že každá metoda `Log*` je správně přepsána. +- **Výjimky při přístupu k souborům:** Zajistěte, aby aplikace měla oprávnění číst/zapisovat jak pro zdrojové, tak výstupní cesty. +- **Logger není připojen:** Parametr `RedactorSettings(logger)` je nezbytný; jeho vynechání zakáže vlastní logování. + +## Praktické aplikace +1. **Reportování souladu:** Exportujte záznamy logu do CSV nebo databáze pro auditní stopy. +2. **Sledování chyb:** Rychle najděte problematické soubory skenováním výstupu `LogError`. +3. **Automatizace workflow:** Spusťte následné procesy (např. upozornění compliance officeru), když je zavoláno `LogWarning`. + +## Úvahy o výkonu +- **Okamžitě uvolňujte proudy** pro uvolnění paměti, zejména při zpracování velkých dávek. +- **Sledujte CPU a paměť** během hromadných redakcí; zvažte paralelní zpracování dokumentů s opatrnou synchronizací loggeru. +- **Zůstaňte aktualizováni:** Novější verze GroupDocs.Redaction často obsahují optimalizace výkonu a další logovací háčky. + +## Závěr + +Implementací **vlastního loggeru c#** získáte podrobný přehled o každém kroku redakčního řetězce, což usnadňuje splnění standardů souladu a ladění problémů. Tento přístup funguje bez problémů s GroupDocs.Redaction pro .NET a lze jej rozšířit tak, aby se integroval s libovolným .NET logovacím frameworkem, který již používáte. + +--- + +## Často kladené otázky + +**Q: Jaký je účel vlastního logování s GroupDocs.Redaction?** +A: Vlastní logování pomáhá sledovat a spravovat redakce pro soulad, sledování chyb a optimalizaci workflow. + +**Q: Jak zacházet s chybami pomocí vlastního loggeru?** +A: Implementujte `LogError` ve své třídě `CustomLogger`; příznak `HasErrors` vám umožní zastavit zpracování, pokud je to potřeba. + +**Q: Lze vlastní logování integrovat s jinými systémy?** +A: Ano, můžete přeposílat logovací zprávy do CRM, ERP nebo centralizovaných monitorovacích nástrojů rozšířením metod loggeru. + +**Q: Jaké jsou běžné úskalí při implementaci vlastního logování?** +A: Nesprávné implementace metod, chybějící `RedactorSettings(logger)` a problémy s oprávněními k souborům jsou nejčastější. + +**Q: Jak vlastní logování zlepšuje workflow redakce dokumentů?** +A: Detailní logy poskytují vizualizaci v reálném čase, usnadňují řešení problémů a splňují požadavky na audit. + +## Zdroje + +- **Dokumentace:** [Dokumentace GroupDocs.Redaction .NET](https://docs.groupdocs.com/redaction/net/) +- **Reference API:** [Reference API GroupDocs.Redaction](https://reference.groupdocs.com/redaction/net) +- **Stáhnout:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Poslední aktualizace:** 2026-03-28 +**Testováno s:** GroupDocs.Redaction 23.11 pro .NET +**Autor:** GroupDocs \ No newline at end of file diff --git a/content/dutch/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/dutch/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..18ab7c2a --- /dev/null +++ b/content/dutch/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,185 @@ +--- +date: '2026-03-28' +description: Leer hoe je een aangepaste logger in C# implementeert in GroupDocs.Redaction + voor .NET, waardoor gedetailleerde aangepaste logging in .NET mogelijk wordt en + compliance‑rapportage eenvoudiger wordt. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Implementeer aangepaste logger c# in GroupDocs.Redaction voor .NET +type: docs +url: /nl/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Implementeer aangepaste logger c# in GroupDocs.Redaction voor .NET + +Het efficiënt beheren van documentredacties is cruciaal, vooral bij het omgaan met gevoelige informatie. In deze gids leer je **hoe je een custom logger c# implementeert** met GroupDocs.Redaction voor .NET, waardoor je volledige controle krijgt over logging, foutafhandeling en audit trails. + +## Snelle antwoorden +- **Wat doet een custom logger c#?** Het legt fouten, waarschuwingen en informatieve berichten vast tijdens de redactie. +- **Welke bibliotheek levert de ILogger interface?** GroupDocs.Redaction voor .NET. +- **Kan ik het geredigeerde document opslaan zonder rasterisatie?** Ja – gebruik `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Heb ik een licentie nodig voor productiegebruik?** Een volledige licentie is vereist voor productie; een proeflicentie is beschikbaar voor evaluatie. +- **Is deze aanpak compatibel met .NET Core / .NET 6+?** Absoluut – dezelfde API werkt zowel op .NET Framework als .NET Core/5/6. + +## Wat is een custom logger c#? +Een **custom logger c#** is een klasse die de `ILogger` interface implementeert die door GroupDocs.Redaction wordt geleverd. Het stelt je in staat logberichten te routeren waar je maar wilt—console, bestand, database of externe monitoringsystemen—terwijl je een duidelijk overzicht krijgt van de redactie‑workflow. + +## Waarom aangepaste logging .net gebruiken met GroupDocs.Redaction? +- **Compliance & Auditing:** Gedetailleerde logs voldoen aan de regelgevingseisen. +- **Error Visibility:** `LogError` en `LogWarning` geven je directe feedback over problemen. +- **Integration Flexibility:** Stuur logs door naar bestaande .NET logging‑frameworks (Serilog, NLog, enz.). + +## Vereisten +- **GroupDocs.Redaction for .NET** geïnstalleerd (zie installatie hieronder). +- Een .NET ontwikkelomgeving (Visual Studio, VS Code of CLI). +- Basiskennis van C# en vertrouwdheid met bestandsstreams. + +## Installatie + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Zoek naar **"GroupDocs.Redaction"** en installeer de nieuwste versie. + +## Licentie‑acquisitie +- **Free Trial:** Test de API met een tijdelijke licentie. +- **Temporary License:** Krijg volledige functionaliteit voor een beperkte periode. +- **Purchase:** Verkrijg een permanente licentie voor productie‑implementaties. + +## Stapsgewijze handleiding + +### Stap 1: Definieer een custom logger‑klasse (log warnings c#) + +Maak een klasse die `ILogger` implementeert. Deze klasse zal fouten, waarschuwingen en informatieve berichten vastleggen. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Uitleg:** De `HasErrors`‑vlag helpt je te bepalen of je moet doorgaan met verwerken. De drie methoden corresponderen met de drie logniveaus die je in de meeste redactie‑scenario's nodig hebt. + +### Stap 2: Bereid bestands‑paden voor en open het bron‑document + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Waarom dit belangrijk is:** Het gebruik van hulpprogram‑methoden houdt je code schoon en zorgt ervoor dat de uitvoermap bestaat voordat je probeert het **geredigeerde document op te slaan**. + +### Stap 3: Pas redacties toe terwijl je de custom logger gebruikt + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Uitleg:** +1. De `Redactor` wordt geïnstantieerd met `RedactorSettings(logger)`, waardoor je `CustomLogger` wordt gekoppeld. +2. Na het toepassen van een redactie controleert de code `logger.HasErrors`. Als er geen fouten zijn opgetreden, wordt het document opgeslagen—wat de logica van **save redacted document** demonstreert zonder rasterisatie. + +### Veelvoorkomende valkuilen & probleemoplossing +- **Missing log output:** Controleer of elke `Log*`‑methode correct is overschreven. +- **File access exceptions:** Zorg ervoor dat de applicatie lees‑/schrijfrechten heeft voor zowel bron‑ als uitvoer‑paden. +- **Logger not wired:** De `RedactorSettings(logger)`‑parameter is essentieel; weglaten ervan schakelt aangepaste logging uit. + +## Praktische toepassingen +1. **Compliance Reporting:** Exporteer logvermeldingen naar een CSV of database voor audit‑trails. +2. **Error Tracking:** Lokaliseer snel problematische bestanden door `LogError`‑output te scannen. +3. **Workflow Automation:** Activeer downstream‑processen (bijv. een compliance‑officier informeren) wanneer `LogWarning` wordt aangeroepen. + +## Prestatie‑overwegingen +- **Dispose streams promptly** om geheugen vrij te maken, vooral bij het verwerken van grote batches. +- **Monitor CPU & memory** tijdens bulk‑redacties; overweeg documenten parallel te verwerken met zorgvuldige logger‑synchronisatie. +- **Stay updated:** Nieuwere versies van GroupDocs.Redaction bevatten vaak prestatie‑optimalisaties en extra logging‑hooks. + +## Conclusie + +Door een **custom logger c#** te implementeren, krijg je gedetailleerd inzicht in elke stap van de redactie‑pipeline, waardoor het makkelijker wordt om te voldoen aan compliance‑normen en problemen te debuggen. De hier getoonde aanpak werkt naadloos met GroupDocs.Redaction voor .NET en kan worden uitgebreid om te integreren met elk .NET logging‑framework dat je al gebruikt. + +--- + +## Veelgestelde vragen + +**Q: Wat is het doel van aangepaste logging met GroupDocs.Redaction?** +A: Aangepaste logging helpt bij het bijhouden en beheren van redacties voor compliance, fouttracking en workflow‑optimalisatie. + +**Q: Hoe ga ik om met fouten met behulp van een custom logger?** +A: Implementeer `LogError` in je `CustomLogger`‑klasse; de `HasErrors`‑vlag stelt je in staat de verwerking te stoppen indien nodig. + +**Q: Kan aangepaste logging worden geïntegreerd met andere systemen?** +A: Ja, je kunt logberichten doorsturen naar CRM, ERP of gecentraliseerde monitoringsystemen door de logger‑methoden uit te breiden. + +**Q: Wat zijn veelvoorkomende valkuilen bij het implementeren van aangepaste logging?** +A: Onjuiste implementaties van methoden, ontbrekende `RedactorSettings(logger)`, en bestands‑toegangsrechten zijn de meest voorkomende. + +**Q: Hoe verbetert aangepaste logging document‑redactie‑workflows?** +A: Gedetailleerde logs bieden realtime‑zichtbaarheid, vereenvoudigen probleemoplossing en voldoen aan audit‑vereisten. + +## Bronnen + +- **Documentatie:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API‑referentie:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Download:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Laatst bijgewerkt:** 2026-03-28 +**Getest met:** GroupDocs.Redaction 23.11 for .NET +**Auteur:** GroupDocs + +--- \ No newline at end of file diff --git a/content/english/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/english/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md index 129a74c2..2f3e132e 100644 --- a/content/english/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md +++ b/content/english/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -1,40 +1,42 @@ --- -title: "Implement Custom Logging in GroupDocs.Redaction for .NET: A Comprehensive Guide" -description: "Learn how to implement custom logging with GroupDocs.Redaction for .NET to enhance document redaction workflows. Discover practical steps and key features." -date: "2025-06-02" +title: "Implement custom logger c# in GroupDocs.Redaction for .NET" +description: "Learn how to implement a custom logger c# in GroupDocs.Redaction for .NET, enabling detailed custom logging .net and easier compliance reporting." +date: "2026-03-28" weight: 1 url: "/net/advanced-redaction/custom-logging-groupdocs-redaction-net/" keywords: -- custom logging GroupDocs.Redaction -- document redaction .NET -- logging in GroupDocs.Redaction +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# type: docs --- -# Implementing Custom Logging in GroupDocs.Redaction for .NET -## Introduction +# Implement custom logger c# in GroupDocs.Redaction for .NET -Managing document redactions efficiently is critical, especially when handling sensitive information. This comprehensive guide will help you implement custom logging in your .NET applications using GroupDocs.Redaction, streamlining the process of tracking and managing redactions. +Managing document redactions efficiently is critical, especially when handling sensitive information. In this guide you’ll learn **how to implement a custom logger c#** with GroupDocs.Redaction for .NET, giving you full control over logging, error handling, and audit trails. -**What You'll Learn:** -- Implementing custom logging for document redactions. -- Key features of the CustomLogger class. -- Practical steps for integrating and utilizing custom logs effectively. +## Quick Answers +- **What does a custom logger c# do?** It captures errors, warnings, and informational messages during redaction. +- **Which library provides the ILogger interface?** GroupDocs.Redaction for .NET. +- **Can I save the redacted document without rasterization?** Yes – use `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Do I need a license for production use?** A full license is required for production; a trial is available for evaluation. +- **Is this approach compatible with .NET Core / .NET 6+?** Absolutely – the same API works across .NET Framework and .NET Core/5/6. -Let's explore how to enhance your document processing capabilities with tailored logging solutions, ensuring a seamless workflow in managing sensitive data. First, ensure you have everything set up correctly. +## What is a custom logger c#? +A **custom logger c#** is a class that implements the `ILogger` interface supplied by GroupDocs.Redaction. It lets you route log messages wherever you need—console, file, database, or external monitoring systems—while giving you a clear view of the redaction workflow. -## Prerequisites - -Before proceeding, make sure you have: -- **Required Libraries and Dependencies:** GroupDocs.Redaction for .NET installed. -- **Environment Setup:** A working .NET environment (e.g., Visual Studio) is necessary to run your code. -- **Knowledge Prerequisites:** Basic understanding of C# programming, file handling in .NET, and familiarity with logging concepts will be beneficial. - -## Setting Up GroupDocs.Redaction for .NET +## Why use custom logging .net with GroupDocs.Redaction? +- **Compliance & Auditing:** Detailed logs satisfy regulatory requirements. +- **Error Visibility:** `LogError` and `LogWarning` give you immediate feedback on problems. +- **Integration Flexibility:** Forward logs to existing .NET logging frameworks (Serilog, NLog, etc.). -### Installation +## Prerequisites +- **GroupDocs.Redaction for .NET** installed (see installation below). +- A .NET development environment (Visual Studio, VS Code, or CLI). +- Basic C# knowledge and familiarity with file streams. -To integrate GroupDocs.Redaction into your project: +## Installation **.NET CLI** ```bash @@ -46,27 +48,19 @@ dotnet add package GroupDocs.Redaction Install-Package GroupDocs.Redaction ``` -**NuGet Package Manager UI** -Search for "GroupDocs.Redaction" and install the latest version directly through the NuGet interface. - -### License Acquisition +**NuGet Package Manager UI** +Search for **"GroupDocs.Redaction"** and install the latest version. -To fully utilize GroupDocs.Redaction, you may acquire a license: -- **Free Trial:** Test out features with a temporary trial license. -- **Temporary License:** Obtain access to all functionalities for a limited time. -- **Purchase:** Buy a full license for continuous use. +## License Acquisition +- **Free Trial:** Test the API with a temporary license. +- **Temporary License:** Get full feature access for a limited period. +- **Purchase:** Obtain a perpetual license for production deployments. -Once your environment is ready and the package installed, let's move on to implementing custom logging. +## Step‑by‑Step Guide -## Implementation Guide +### Step 1: Define a custom logger class (log warnings c#) -### Custom Logging Feature - -Implementing custom logging with GroupDocs.Redaction allows you to track and manage redaction processes efficiently. Here’s how: - -#### Step 1: Define a Custom Logger Class - -Create a class that implements the `ILogger` interface, responsible for handling log messages during the redaction process. +Create a class that implements `ILogger`. This class will capture errors, warnings, and informational messages. ```csharp using System; @@ -97,23 +91,18 @@ class CustomLogger : ILogger } ``` -**Explanation:** This custom logger class provides methods to log errors, warnings, and information. The `HasErrors` property tracks if any errors occurred during the redaction process. - -#### Step 2: Apply Redactions with Custom Logging +**Explanation:** The `HasErrors` flag helps you decide whether to continue processing. The three methods correspond to the three log levels you’ll need in most redaction scenarios. -Utilize your custom logger within a document's redaction workflow: - -1. **Open the Source File for Redaction:** - - Ensure access to both input and output file paths. +### Step 2: Prepare file paths and open the source document ```csharp string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); string outputFile = Utils.GetOutputFile(sourceFile); ``` -2. **Initialize Redactor with Custom Logger:** +**Why this matters:** Using utility methods keeps your code clean and ensures the output folder exists before you attempt to **save redacted document**. -Using the `CustomLogger` instance, initialize the `Redactor`. +### Step 3: Apply redactions while using the custom logger ```csharp using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) @@ -137,55 +126,61 @@ using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite } ``` -**Explanation:** This snippet demonstrates opening a document for redaction and utilizing your custom logger to track any issues. The `Redactor` instance is initialized with logging settings to capture error or warning messages. +**Explanation:** +1. The `Redactor` is instantiated with `RedactorSettings(logger)`, linking your `CustomLogger`. +2. After applying a redaction, the code checks `logger.HasErrors`. If no errors occurred, the document is saved—demonstrating **save redacted document** logic without rasterization. -### Troubleshooting Tips +### Common Pitfalls & Troubleshooting -- **Logging Issues:** Ensure that the log methods are correctly implemented in your `CustomLogger`. Missing logs could indicate an issue with method calls. -- **File Access Errors:** Verify file paths and permissions. Inaccessible files can lead to exceptions during the redaction process. +- **Missing log output:** Verify that each `Log*` method is correctly overridden. +- **File access exceptions:** Ensure the application has read/write permissions for both source and output paths. +- **Logger not wired:** The `RedactorSettings(logger)` parameter is essential; omitting it disables custom logging. ## Practical Applications -Implementing custom logging is beneficial in various scenarios: - -1. **Compliance Reporting:** Keep detailed logs of all redactions performed, aiding compliance audits. -2. **Error Tracking:** Quickly identify and resolve issues with document processing workflows. -3. **Workflow Optimization:** Analyze logs to optimize redaction processes by identifying common errors or inefficiencies. - -Integrating custom logging can also facilitate seamless integration with other systems like CRM or ERP solutions that require robust logging mechanisms for data handling. +1. **Compliance Reporting:** Export log entries to a CSV or database for audit trails. +2. **Error Tracking:** Quickly locate problematic files by scanning `LogError` output. +3. **Workflow Automation:** Trigger downstream processes (e.g., notifying a compliance officer) when `LogWarning` is invoked. ## Performance Considerations -When using GroupDocs.Redaction, consider: -- **Optimizing Memory Usage:** Ensure efficient memory management by disposing of streams and redactor instances promptly. -- **Resource Management:** Monitor resource usage to prevent bottlenecks during large-scale document processing tasks. -- **Best Practices:** Regularly update GroupDocs.Redaction to benefit from performance enhancements in newer versions. +- **Dispose streams promptly** to free memory, especially when processing large batches. +- **Monitor CPU & memory** during bulk redactions; consider processing documents in parallel with careful logger synchronization. +- **Stay updated:** Newer versions of GroupDocs.Redaction often include performance optimizations and additional logging hooks. ## Conclusion -Implementing custom logging with GroupDocs.Redaction for .NET enhances your ability to manage and track redactions effectively. With the steps outlined above, you can create a robust logging mechanism tailored to your needs. +By implementing a **custom logger c#**, you gain granular insight into every step of the redaction pipeline, making it easier to meet compliance standards and debug issues. The approach shown here works seamlessly with GroupDocs.Redaction for .NET and can be extended to integrate with any .NET logging framework you already use. -To further explore GroupDocs.Redaction capabilities, consider delving into additional features like document preview or advanced search functionalities. Try implementing these solutions in your projects and see how they streamline your document processing workflows! +--- -## FAQ Section +## Frequently Asked Questions -1. **What is the purpose of custom logging with GroupDocs.Redaction?** - - Custom logging helps track and manage redactions for compliance, error tracking, and workflow optimization. +**Q: What is the purpose of custom logging with GroupDocs.Redaction?** +A: Custom logging helps track and manage redactions for compliance, error tracking, and workflow optimization. -2. **How do I handle errors using a custom logger?** - - Implement `LogError` in your `CustomLogger` class to capture and respond to any issues during the redaction process. +**Q: How do I handle errors using a custom logger?** +A: Implement `LogError` in your `CustomLogger` class; the `HasErrors` flag lets you halt processing if needed. -3. **Can custom logging be integrated with other systems?** - - Yes, logs can be formatted or exported for integration with CRM, ERP, or other data management systems. +**Q: Can custom logging be integrated with other systems?** +A: Yes, you can forward log messages to CRM, ERP, or centralized monitoring tools by extending the logger methods. -4. **What are some common pitfalls when implementing custom logging?** - - Common issues include incorrect logger method implementations and file access errors due to permission settings. +**Q: What are some common pitfalls when implementing custom logging?** +A: Incorrect method implementations, missing `RedactorSettings(logger)`, and file permission issues are the most frequent. -5. **How does custom logging improve document redaction workflows?** - - By providing detailed insights into the redaction process, allowing for real-time adjustments and compliance assurance. +**Q: How does custom logging improve document redaction workflows?** +A: Detailed logs provide real‑time visibility, simplify troubleshooting, and satisfy audit requirements. ## Resources - **Documentation:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) - **API Reference:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) - **Download:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Last Updated:** 2026-03-28 +**Tested With:** GroupDocs.Redaction 23.11 for .NET +**Author:** GroupDocs + +--- \ No newline at end of file diff --git a/content/french/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/french/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..9250593f --- /dev/null +++ b/content/french/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,180 @@ +--- +date: '2026-03-28' +description: Apprenez à implémenter un logger personnalisé C# dans GroupDocs.Redaction + pour .NET, permettant une journalisation personnalisée détaillée et une génération + de rapports de conformité plus simple. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Implémenter un logger personnalisé C# dans GroupDocs.Redaction pour .NET +type: docs +url: /fr/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Implémenter un logger personnalisé c# dans GroupDocs.Redaction pour .NET + +Gérer les censures de documents de manière efficace est essentiel, surtout lorsqu’il s’agit d’informations sensibles. Dans ce guide, vous apprendrez **comment implémenter un logger personnalisé c#** avec GroupDocs.Redaction pour .NET, vous offrant un contrôle complet sur la journalisation, la gestion des erreurs et les traces d’audit. + +## Réponses rapides +- **Que fait un logger personnalisé c# ?** Il capture les erreurs, les avertissements et les messages d'information pendant la censure. +- **Quelle bibliothèque fournit l'interface ILogger ?** GroupDocs.Redaction pour .NET. +- **Puis-je enregistrer le document censuré sans rasterisation ?** Oui – utilisez `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Ai-je besoin d'une licence pour une utilisation en production ?** Une licence complète est requise pour la production ; une version d'essai est disponible pour l'évaluation. +- **Cette approche est‑elle compatible avec .NET Core / .NET 6+ ?** Absolument – la même API fonctionne sur .NET Framework et .NET Core/5/6. + +## Qu'est‑ce qu'un logger personnalisé c# ? +Un **logger personnalisé c#** est une classe qui implémente l'interface `ILogger` fournie par GroupDocs.Redaction. Il vous permet d'acheminer les messages de journalisation où vous le souhaitez — console, fichier, base de données ou systèmes de surveillance externes — tout en vous offrant une vue claire du flux de travail de la censure. + +## Pourquoi utiliser la journalisation personnalisée .net avec GroupDocs.Redaction ? +- **Conformité & Audit :** Des journaux détaillés répondent aux exigences réglementaires. +- **Visibilité des erreurs :** `LogError` et `LogWarning` vous donnent un retour immédiat sur les problèmes. +- **Flexibilité d'intégration :** Transférez les journaux vers les frameworks de journalisation .NET existants (Serilog, NLog, etc.). + +## Prérequis +- **GroupDocs.Redaction pour .NET** installé (voir l'installation ci‑dessous). +- Un environnement de développement .NET (Visual Studio, VS Code ou CLI). +- Connaissances de base en C# et familiarité avec les flux de fichiers. + +## Installation + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Gestionnaire de packages** +```powershell +Install-Package GroupDocs.Redaction +``` + +**Interface du gestionnaire de packages NuGet** +Recherchez **"GroupDocs.Redaction"** et installez la dernière version. + +## Acquisition de licence +- **Essai gratuit :** Testez l'API avec une licence temporaire. +- **Licence temporaire :** Obtenez un accès complet aux fonctionnalités pendant une période limitée. +- **Achat :** Procurez-vous une licence perpétuelle pour les déploiements en production. + +## Guide étape par étape + +### Étape 1 : Définir une classe de logger personnalisée (log warnings c#) +Créez une classe qui implémente `ILogger`. Cette classe capturera les erreurs, les avertissements et les messages d'information. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Explication :** Le drapeau `HasErrors` vous aide à décider s'il faut poursuivre le traitement. Les trois méthodes correspondent aux trois niveaux de journalisation dont vous aurez besoin dans la plupart des scénarios de censure. + +### Étape 2 : Préparer les chemins de fichiers et ouvrir le document source +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Pourquoi c'est important :** L'utilisation de méthodes utilitaires garde votre code propre et garantit que le dossier de sortie existe avant d'essayer de **enregistrer le document censuré**. + +### Étape 3 : Appliquer les censures en utilisant le logger personnalisé +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Explication :** +1. Le `Redactor` est instancié avec `RedactorSettings(logger)`, liant votre `CustomLogger`. +2. Après avoir appliqué une censure, le code vérifie `logger.HasErrors`. S'il n'y a pas eu d'erreurs, le document est enregistré — démontrant la logique de **enregistrement du document censuré** sans rasterisation. + +### Pièges courants & Dépannage +- **Sortie de journal manquante :** Vérifiez que chaque méthode `Log*` est correctement surchargée. +- **Exceptions d'accès aux fichiers :** Assurez‑vous que l'application possède les permissions de lecture/écriture pour les chemins source et de sortie. +- **Logger non connecté :** Le paramètre `RedactorSettings(logger)` est essentiel ; le omettre désactive la journalisation personnalisée. + +## Applications pratiques +1. **Rapports de conformité :** Exportez les entrées de journal vers un CSV ou une base de données pour les traces d'audit. +2. **Suivi des erreurs :** Localisez rapidement les fichiers problématiques en analysant la sortie de `LogError`. +3. **Automatisation du flux de travail :** Déclenchez des processus en aval (par ex., notifier un responsable conformité) lorsque `LogWarning` est invoqué. + +## Considérations de performance +- **Libérez les flux rapidement** pour libérer la mémoire, surtout lors du traitement de gros lots. +- **Surveillez le CPU & la mémoire** pendant les censures en masse ; envisagez de traiter les documents en parallèle avec une synchronisation prudente du logger. +- **Restez à jour :** Les versions plus récentes de GroupDocs.Redaction incluent souvent des optimisations de performance et des points d'extension de journalisation supplémentaires. + +## Conclusion +En implémentant un **logger personnalisé c#**, vous obtenez une visibilité granulaire sur chaque étape du pipeline de censure, facilitant le respect des normes de conformité et le débogage des problèmes. L'approche présentée ici fonctionne parfaitement avec GroupDocs.Redaction pour .NET et peut être étendue pour s'intégrer à n'importe quel framework de journalisation .NET que vous utilisez déjà. + +--- + +## Questions fréquemment posées + +**Q : Quel est le but de la journalisation personnalisée avec GroupDocs.Redaction ?** +R : La journalisation personnalisée aide à suivre et gérer les censures pour la conformité, le suivi des erreurs et l'optimisation du flux de travail. + +**Q : Comment gérer les erreurs avec un logger personnalisé ?** +R : Implémentez `LogError` dans votre classe `CustomLogger` ; le drapeau `HasErrors` vous permet d’arrêter le traitement si nécessaire. + +**Q : La journalisation personnalisée peut‑elle être intégrée à d'autres systèmes ?** +R : Oui, vous pouvez transmettre les messages de journalisation à un CRM, ERP ou à des outils de surveillance centralisés en étendant les méthodes du logger. + +**Q : Quels sont les pièges courants lors de l'implémentation de la journalisation personnalisée ?** +R : Des implémentations de méthodes incorrectes, l'absence de `RedactorSettings(logger)` et des problèmes de permissions de fichiers sont les plus fréquents. + +**Q : Comment la journalisation personnalisée améliore‑t‑elle les flux de travail de censure de documents ?** +R : Des journaux détaillés offrent une visibilité en temps réel, simplifient le dépannage et répondent aux exigences d’audit. + +## Ressources +- **Documentation :** [Documentation .NET de GroupDocs.Redaction](https://docs.groupdocs.com/redaction/net/) +- **Référence API :** [Référence API de GroupDocs.Redaction](https://reference.groupdocs.com/redaction/net) +- **Téléchargement :** [GroupDocs.Redaction pour .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Dernière mise à jour :** 2026-03-28 +**Testé avec :** GroupDocs.Redaction 23.11 pour .NET +**Auteur :** GroupDocs + +--- \ No newline at end of file diff --git a/content/german/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/german/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..95e38cab --- /dev/null +++ b/content/german/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,182 @@ +--- +date: '2026-03-28' +description: Erfahren Sie, wie Sie einen benutzerdefinierten Logger in C# in GroupDocs.Redaction + für .NET implementieren, um detailliertes benutzerdefiniertes Logging in .NET zu + ermöglichen und die Compliance-Berichterstattung zu erleichtern. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Implementieren Sie einen benutzerdefinierten Logger in C# in GroupDocs.Redaction + für .NET +type: docs +url: /de/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Benutzerdefinierten Logger c# in GroupDocs.Redaction für .NET implementieren + +Die effiziente Verwaltung von Dokumentenredaktionen ist entscheidend, insbesondere beim Umgang mit sensiblen Informationen. In diesem Leitfaden lernen Sie **wie man einen benutzerdefinierten Logger c#** mit GroupDocs.Redaction für .NET implementiert, wodurch Sie die volle Kontrolle über Protokollierung, Fehlerbehandlung und Prüfpfade erhalten. + +## Schnelle Antworten +- **Was macht ein benutzerdefinierter Logger c#?** Er erfasst Fehler, Warnungen und Informationsmeldungen während der Redaktion. +- **Welche Bibliothek stellt die ILogger‑Schnittstelle bereit?** GroupDocs.Redaction für .NET. +- **Kann ich das redigierte Dokument ohne Rasterisierung speichern?** Ja – verwenden Sie `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Benötige ich eine Lizenz für den Produktionseinsatz?** Für die Produktion ist eine Voll‑Lizenz erforderlich; eine Testversion ist zur Evaluierung verfügbar. +- **Ist dieser Ansatz mit .NET Core / .NET 6+ kompatibel?** Absolut – dieselbe API funktioniert sowohl unter .NET Framework als auch unter .NET Core/5/6. + +## Was ist ein benutzerdefinierter Logger c#? +Ein **benutzerdefinierter Logger c#** ist eine Klasse, die die von GroupDocs.Redaction bereitgestellte `ILogger`‑Schnittstelle implementiert. Sie ermöglicht es Ihnen, Protokollnachrichten dorthin zu leiten, wo Sie sie benötigen – Konsole, Datei, Datenbank oder externe Überwachungssysteme – und gibt Ihnen gleichzeitig einen klaren Überblick über den Redaktionsablauf. + +## Warum benutzerdefinierte Protokollierung .net mit GroupDocs.Redaction verwenden? +- **Compliance & Auditing:** Detaillierte Protokolle erfüllen regulatorische Anforderungen. +- **Fehlertransparenz:** `LogError` und `LogWarning` geben Ihnen sofortiges Feedback zu Problemen. +- **Integrationsflexibilität:** Leiten Sie Protokolle an bestehende .NET‑Protokollierungsframeworks weiter (Serilog, NLog usw.). + +## Voraussetzungen +- **GroupDocs.Redaction für .NET** installiert (siehe Installation unten). +- Eine .NET‑Entwicklungsumgebung (Visual Studio, VS Code oder CLI). +- Grundkenntnisse in C# und Vertrautheit mit Dateistreams. + +## Installation + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Suchen Sie nach **"GroupDocs.Redaction"** und installieren Sie die neueste Version. + +## Lizenzbeschaffung +- **Kostenlose Testversion:** Testen Sie die API mit einer temporären Lizenz. +- **Temporäre Lizenz:** Erhalten Sie vollen Funktionszugriff für einen begrenzten Zeitraum. +- **Kauf:** Erwerben Sie eine unbefristete Lizenz für Produktionseinsätze. + +## Schritt‑für‑Schritt‑Anleitung + +### Schritt 1: Definieren einer benutzerdefinierten Logger‑Klasse (Log‑Warnungen c#) +Erstellen Sie eine Klasse, die `ILogger` implementiert. Diese Klasse erfasst Fehler, Warnungen und Informationsmeldungen. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Erklärung:** Das `HasErrors`‑Flag hilft Ihnen zu entscheiden, ob die Verarbeitung fortgesetzt werden soll. Die drei Methoden entsprechen den drei Protokollstufen, die Sie in den meisten Redaktionsszenarien benötigen. + +### Schritt 2: Dateipfade vorbereiten und das Quellendokument öffnen +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Warum das wichtig ist:** Die Verwendung von Hilfsmethoden hält Ihren Code sauber und stellt sicher, dass der Ausgabordner existiert, bevor Sie versuchen, das **redigierte Dokument zu speichern**. + +### Schritt 3: Redaktionen anwenden und dabei den benutzerdefinierten Logger verwenden +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Erklärung:** +1. Der `Redactor` wird mit `RedactorSettings(logger)` instanziiert, wodurch Ihr `CustomLogger` verknüpft wird. +2. Nach dem Anwenden einer Redaktion prüft der Code `logger.HasErrors`. Wenn keine Fehler aufgetreten sind, wird das Dokument gespeichert – dies demonstriert die Logik zum **Speichern des redigierten Dokuments** ohne Rasterisierung. + +## Häufige Fallstricke & Fehlersuche +- **Fehlende Protokollausgabe:** Stellen Sie sicher, dass jede `Log*`‑Methode korrekt überschrieben wurde. +- **Dateizugriffs‑Ausnahmen:** Stellen Sie sicher, dass die Anwendung Lese‑/Schreibrechte für sowohl Quell‑ als auch Ausgabepfade hat. +- **Logger nicht verbunden:** Der Parameter `RedactorSettings(logger)` ist essenziell; das Weglassen deaktiviert die benutzerdefinierte Protokollierung. + +## Praktische Anwendungen +1. **Compliance‑Berichterstattung:** Exportieren Sie Protokolleinträge in eine CSV‑Datei oder Datenbank für Prüfpfade. +2. **Fehlerverfolgung:** Finden Sie problematische Dateien schnell, indem Sie die `LogError`‑Ausgabe durchsuchen. +3. **Workflow‑Automatisierung:** Lösen Sie nachgelagerte Prozesse aus (z. B. Benachrichtigung eines Compliance‑Beauftragten), wenn `LogWarning` aufgerufen wird. + +## Leistungsüberlegungen +- **Streams sofort freigeben**, um Speicher zu schonen, besonders bei der Verarbeitung großer Stapel. +- **CPU‑ & Speicherverbrauch überwachen** während Massenredaktionen; erwägen Sie die parallele Verarbeitung von Dokumenten bei sorgfältiger Logger‑Synchronisation. +- **Aktuell bleiben:** Neuere Versionen von GroupDocs.Redaction enthalten häufig Leistungsoptimierungen und zusätzliche Protokoll‑Hooks. + +## Fazit +Durch die Implementierung eines **benutzerdefinierten Logger c#** erhalten Sie detaillierte Einblicke in jeden Schritt der Redaktionspipeline, was das Erreichen von Compliance‑Standards und das Debuggen von Problemen erleichtert. Der hier gezeigte Ansatz funktioniert nahtlos mit GroupDocs.Redaction für .NET und kann erweitert werden, um sich in jedes bereits genutzte .NET‑Protokollierungsframework zu integrieren. + +--- + +## Häufig gestellte Fragen + +**Q: Was ist der Zweck der benutzerdefinierten Protokollierung mit GroupDocs.Redaction?** +A: Die benutzerdefinierte Protokollierung hilft, Redaktionen für Compliance, Fehlerverfolgung und Workflow‑Optimierung zu verfolgen und zu verwalten. + +**Q: Wie gehe ich mit Fehlern unter Verwendung eines benutzerdefinierten Loggers um?** +A: Implementieren Sie `LogError` in Ihrer `CustomLogger`‑Klasse; das `HasErrors`‑Flag ermöglicht es Ihnen, die Verarbeitung bei Bedarf zu stoppen. + +**Q: Kann benutzerdefinierte Protokollierung in andere Systeme integriert werden?** +A: Ja, Sie können Protokollnachrichten an CRM-, ERP‑ oder zentrale Überwachungstools weiterleiten, indem Sie die Logger‑Methoden erweitern. + +**Q: Was sind häufige Fallstricke bei der Implementierung benutzerdefinierter Protokollierung?** +A: Falsche Methodenumsetzungen, fehlendes `RedactorSettings(logger)` und Dateiberechtigungsprobleme sind die häufigsten. + +**Q: Wie verbessert benutzerdefinierte Protokollierung die Dokumenten‑Redaktions‑Workflows?** +A: Detaillierte Protokolle bieten Echtzeit‑Transparenz, vereinfachen die Fehlersuche und erfüllen Prüfungsanforderungen. + +## Ressourcen + +- **Dokumentation:** [GroupDocs.Redaction .NET Dokumentation](https://docs.groupdocs.com/redaction/net/) +- **API‑Referenz:** [GroupDocs.Redaction API Referenz](https://reference.groupdocs.com/redaction/net) +- **Download:** [GroupDocs.Redaction für .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Zuletzt aktualisiert:** 2026-03-28 +**Getestet mit:** GroupDocs.Redaction 23.11 für .NET +**Autor:** GroupDocs + +--- \ No newline at end of file diff --git a/content/greek/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/greek/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..ca700656 --- /dev/null +++ b/content/greek/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,183 @@ +--- +date: '2026-03-28' +description: Μάθετε πώς να υλοποιήσετε έναν προσαρμοσμένο logger C# στο GroupDocs.Redaction + για .NET, επιτρέποντας λεπτομερή προσαρμοσμένη καταγραφή .NET και πιο εύκολη αναφορά + συμμόρφωσης. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Υλοποίηση προσαρμοσμένου καταγραφέα c# στο GroupDocs.Redaction για .NET +type: docs +url: /el/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Υλοποίηση προσαρμοσμένου καταγραφέα c# στο GroupDocs.Redaction για .NET + +Η διαχείριση των διαγραφών εγγράφων αποδοτικά είναι κρίσιμη, ειδικά όταν χειριζόμαστε ευαίσθητες πληροφορίες. Σε αυτόν τον οδηγό θα μάθετε **πώς να υλοποιήσετε έναν προσαρμοσμένο καταγραφέα c#** με το GroupDocs.Redaction για .NET, παρέχοντάς σας πλήρη έλεγχο στην καταγραφή, τη διαχείριση σφαλμάτων και τα αρχεία ελέγχου. + +## Γρήγορες Απαντήσεις +- **Τι κάνει ένας προσαρμοσμένος καταγραφέας c#;** Καταγράφει σφάλματα, προειδοποιήσεις και πληροφοριακά μηνύματα κατά τη διάρκεια της διαγραφής. +- **Ποια βιβλιοθήκη παρέχει το interface ILogger;** GroupDocs.Redaction for .NET. +- **Μπορώ να αποθηκεύσω το διαγραμμένο έγγραφο χωρίς rasterization;** Ναι – χρησιμοποιήστε `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Χρειάζομαι άδεια για παραγωγική χρήση;** Απαιτείται πλήρης άδεια για παραγωγή· υπάρχει δοκιμαστική άδεια για αξιολόγηση. +- **Είναι αυτή η προσέγγιση συμβατή με .NET Core / .NET 6+;** Απόλυτα – το ίδιο API λειτουργεί σε .NET Framework και .NET Core/5/6. + +## Τι είναι ένας προσαρμοσμένος καταγραφέας c#; +Ένας **custom logger c#** είναι μια κλάση που υλοποιεί το interface `ILogger` που παρέχεται από το GroupDocs.Redaction. Σας επιτρέπει να κατευθύνετε τα μηνύματα καταγραφής όπου χρειάζεστε—στην κονσόλα, σε αρχείο, σε βάση δεδομένων ή σε εξωτερικά συστήματα παρακολούθησης—παρέχοντας μια σαφή εικόνα της ροής εργασίας της διαγραφής. + +## Γιατί να χρησιμοποιήσετε προσαρμοσμένη καταγραφή .net με το GroupDocs.Redaction; +- **Συμμόρφωση & Έλεγχος:** Αναλυτικές καταγραφές ικανοποιούν τις κανονιστικές απαιτήσεις. +- **Ορατότητα Σφαλμάτων:** `LogError` και `LogWarning` παρέχουν άμεση ανάδραση για προβλήματα. +- **Ευελιξία Ενσωμάτωσης:** Προωθήστε τις καταγραφές σε υπάρχοντα .NET frameworks καταγραφής (Serilog, NLog, κλπ.). + +## Προαπαιτούμενα +- **GroupDocs.Redaction for .NET** εγκατεστημένο (δείτε την εγκατάσταση παρακάτω). +- Ένα περιβάλλον ανάπτυξης .NET (Visual Studio, VS Code ή CLI). +- Βασικές γνώσεις C# και εξοικείωση με ροές αρχείων. + +## Εγκατάσταση + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Διαχειριστής Πακέτων** +```powershell +Install-Package GroupDocs.Redaction +``` + +**Διαχειριστής Πακέτων NuGet UI** +Αναζητήστε το **"GroupDocs.Redaction"** και εγκαταστήστε την πιο πρόσφατη έκδοση. + +## Απόκτηση Άδειας +- **Δωρεάν Δοκιμή:** Δοκιμάστε το API με προσωρινή άδεια. +- **Προσωρινή Άδεια:** Λάβετε πλήρη πρόσβαση στις λειτουργίες για περιορισμένο χρονικό διάστημα. +- **Αγορά:** Αποκτήστε μόνιμη άδεια για παραγωγικές εγκαταστάσεις. + +## Οδηγός Βήμα‑βήμα + +### Βήμα 1: Ορισμός προσαρμοσμένης κλάσης καταγραφέα (log warnings c#) + +Δημιουργήστε μια κλάση που υλοποιεί το `ILogger`. Αυτή η κλάση θα καταγράφει σφάλματα, προειδοποιήσεις και πληροφοριακά μηνύματα. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Επεξήγηση:** Η σημαία `HasErrors` σας βοηθά να αποφασίσετε αν θα συνεχίσετε την επεξεργασία. Οι τρεις μέθοδοι αντιστοιχούν στα τρία επίπεδα καταγραφής που θα χρειαστείτε στις περισσότερες περιπτώσεις διαγραφής. + +### Βήμα 2: Προετοιμασία διαδρομών αρχείων και άνοιγμα του πηγαίου εγγράφου + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Γιατί είναι σημαντικό:** Η χρήση βοηθητικών μεθόδων διατηρεί τον κώδικά σας καθαρό και εξασφαλίζει ότι ο φάκελος εξόδου υπάρχει πριν προσπαθήσετε να **αποθηκεύσετε το διαγραμμένο έγγραφο**. + +### Βήμα 3: Εφαρμογή διαγραφών χρησιμοποιώντας τον προσαρμοσμένο καταγραφέα + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Επεξήγηση:** +1. Το `Redactor` δημιουργείται με `RedactorSettings(logger)`, συνδέοντας το `CustomLogger` σας. +2. Μετά την εφαρμογή μιας διαγραφής, ο κώδικας ελέγχει το `logger.HasErrors`. Αν δεν προέκυψαν σφάλματα, το έγγραφο αποθηκεύεται—δείχνοντας τη λογική **αποθήκευσης διαγραμμένου εγγράφου** χωρίς rasterization. + +### Συχνά Προβλήματα & Επίλυση +- **Απουσία εξόδου καταγραφής:** Επαληθεύστε ότι κάθε μέθοδος `Log*` έχει παρακαμφθεί σωστά. +- **Εξαιρέσεις πρόσβασης αρχείου:** Βεβαιωθείτε ότι η εφαρμογή έχει δικαιώματα ανάγνωσης/εγγραφής για τις διαδρομές πηγής και εξόδου. +- **Ο καταγραφέας δεν είναι συνδεδεμένος:** Η παράμετρος `RedactorSettings(logger)` είναι απαραίτητη· η παράλειψή της απενεργοποιεί την προσαρμοσμένη καταγραφή. + +## Πρακτικές Εφαρμογές +1. **Αναφορά Συμμόρφωσης:** Εξαγωγή εγγραφών καταγραφής σε CSV ή βάση δεδομένων για αρχεία ελέγχου. +2. **Παρακολούθηση Σφαλμάτων:** Εντοπίστε γρήγορα προβληματικά αρχεία σκανάροντας την έξοδο `LogError`. +3. **Αυτοματοποίηση Ροής Εργασίας:** Ενεργοποιήστε επόμενες διαδικασίες (π.χ., ειδοποίηση υπεύθυνου συμμόρφωσης) όταν κληθεί το `LogWarning`. + +## Σκέψεις Απόδοσης +- **Απελευθερώστε τις ροές άμεσα** για να ελευθερώσετε μνήμη, ειδικά όταν επεξεργάζεστε μεγάλες παρτίδες. +- **Παρακολουθήστε CPU & μνήμη** κατά τις μαζικές διαγραφές· σκεφτείτε την επεξεργασία εγγράφων παράλληλα με προσεκτικό συγχρονισμό του καταγραφέα. +- **Μείνετε ενημερωμένοι:** Νεότερες εκδόσεις του GroupDocs.Redaction συχνά περιλαμβάνουν βελτιστοποιήσεις απόδοσης και επιπλέον hooks καταγραφής. + +## Συμπέρασμα + +Με την υλοποίηση ενός **custom logger c#**, αποκτάτε λεπτομερή εικόνα σε κάθε βήμα της αλυσίδας διαγραφής, καθιστώντας πιο εύκολο το να πληρούνται τα πρότυπα συμμόρφωσης και η εντοπισμός σφαλμάτων. Η προσέγγιση που παρουσιάζεται εδώ λειτουργεί αβίαστα με το GroupDocs.Redaction για .NET και μπορεί να επεκταθεί για ενσωμάτωση με οποιοδήποτε .NET framework καταγραφής που ήδη χρησιμοποιείτε. + +--- + +## Συχνές Ερωτήσεις + +**Q: Ποιος είναι ο σκοπός της προσαρμοσμένης καταγραφής με το GroupDocs.Redaction;** +A: Η προσαρμοσμένη καταγραφή βοηθά στην παρακολούθηση και διαχείριση των διαγραφών για συμμόρφωση, εντοπισμό σφαλμάτων και βελτιστοποίηση της ροής εργασίας. + +**Q: Πώς διαχειρίζομαι τα σφάλματα χρησιμοποιώντας έναν προσαρμοσμένο καταγραφέα;** +A: Υλοποιήστε το `LogError` στην κλάση `CustomLogger`; η σημαία `HasErrors` σας επιτρέπει να διακόψετε την επεξεργασία αν χρειάζεται. + +**Q: Μπορεί η προσαρμοσμένη καταγραφή να ενσωματωθεί με άλλα συστήματα;** +A: Ναι, μπορείτε να προωθήσετε τα μηνύματα καταγραφής σε CRM, ERP ή κεντρικά εργαλεία παρακολούθησης επεκτείνοντας τις μεθόδους του καταγραφέα. + +**Q: Ποια είναι μερικά κοινά προβλήματα κατά την υλοποίηση προσαρμοσμένης καταγραφής;** +A: Λανθασμένες υλοποιήσεις μεθόδων, έλλειψη `RedactorSettings(logger)`, και προβλήματα δικαιωμάτων αρχείων είναι τα πιο συχνά. + +**Q: Πώς η προσαρμοσμένη καταγραφή βελτιώνει τις ροές εργασίας διαγραφής εγγράφων;** +A: Αναλυτικές καταγραφές παρέχουν ορατότητα σε πραγματικό χρόνο, απλοποιούν την αντιμετώπιση προβλημάτων και ικανοποιούν τις απαιτήσεις ελέγχου. + +## Πόροι + +- **Τεκμηρίωση:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **Αναφορά API:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Λήψη:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Τελευταία Ενημέρωση:** 2026-03-28 +**Δοκιμή Με:** GroupDocs.Redaction 23.11 for .NET +**Συγγραφέας:** GroupDocs \ No newline at end of file diff --git a/content/hindi/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/hindi/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..12b12e38 --- /dev/null +++ b/content/hindi/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,177 @@ +--- +date: '2026-03-28' +description: GroupDocs.Redaction for .NET में कस्टम लॉगर C# को कैसे लागू करें, जिससे + विस्तृत कस्टम लॉगिंग और आसान अनुपालन रिपोर्टिंग संभव हो। +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: .NET के लिए GroupDocs.Redaction में कस्टम लॉगर C# लागू करें +type: docs +url: /hi/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# GroupDocs.Redaction के लिए .NET में कस्टम लॉगर c# लागू करें + +दस्तावेज़ रिडैक्शन को कुशलतापूर्वक प्रबंधित करना अत्यंत महत्वपूर्ण है, विशेष रूप से संवेदनशील जानकारी को संभालते समय। इस गाइड में आप GroupDocs.Redaction for .NET के साथ **कस्टम लॉगर c# को कैसे लागू करें** सीखेंगे, जिससे आपको लॉगिंग, त्रुटि प्रबंधन और ऑडिट ट्रेल्स पर पूर्ण नियंत्रण मिलेगा। + +## त्वरित उत्तर +- **कस्टम लॉगर c# क्या करता है?** यह रिडैक्शन के दौरान त्रुटियों, चेतावनियों और सूचना संदेशों को कैप्चर करता है। +- **कौन सी लाइब्रेरी ILogger इंटरफ़ेस प्रदान करती है?** GroupDocs.Redaction for .NET। +- **क्या मैं रास्टराइज़ेशन के बिना रिडैक्टेड दस्तावेज़ सहेज सकता हूँ?** हाँ – `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })` का उपयोग करें। +- **क्या उत्पादन उपयोग के लिए लाइसेंस की आवश्यकता है?** उत्पादन के लिए पूर्ण लाइसेंस आवश्यक है; मूल्यांकन के लिए एक ट्रायल उपलब्ध है। +- **क्या यह तरीका .NET Core / .NET 6+ के साथ संगत है?** बिल्कुल – वही API .NET Framework और .NET Core/5/6 में काम करता है। + +## कस्टम लॉगर c# क्या है? +एक **कस्टम लॉगर c#** वह क्लास है जो GroupDocs.Redaction द्वारा प्रदान किए गए `ILogger` इंटरफ़ेस को लागू करता है। यह आपको लॉग संदेशों को जहाँ भी आवश्यक हो—कंसोल, फ़ाइल, डेटाबेस, या बाहरी मॉनिटरिंग सिस्टम—पर रूट करने की सुविधा देता है, साथ ही रिडैक्शन वर्कफ़्लो का स्पष्ट दृश्य प्रदान करता है। + +## GroupDocs.Redaction के साथ कस्टम लॉगिंग .net क्यों उपयोग करें? +- **अनुपालन एवं ऑडिटिंग:** विस्तृत लॉग नियामक आवश्यकताओं को पूरा करते हैं। +- **त्रुटि दृश्यता:** `LogError` और `LogWarning` समस्याओं पर तुरंत प्रतिक्रिया देते हैं। +- **एकीकरण लचीलापन:** लॉग को मौजूदा .NET लॉगिंग फ्रेमवर्क (Serilog, NLog, आदि) में फ़ॉरवर्ड करें। + +## पूर्वापेक्षाएँ +- **GroupDocs.Redaction for .NET** स्थापित हो (नीचे इंस्टॉलेशन देखें)। +- एक .NET विकास वातावरण (Visual Studio, VS Code, या CLI)। +- बेसिक C# ज्ञान और फ़ाइल स्ट्रीम्स की परिचितता। + +## इंस्टॉलेशन + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +**"GroupDocs.Redaction"** को खोजें और नवीनतम संस्करण स्थापित करें। + +## लाइसेंस प्राप्ति +- **फ्री ट्रायल:** अस्थायी लाइसेंस के साथ API का परीक्षण करें। +- **टेम्पररी लाइसेंस:** सीमित अवधि के लिए सभी फीचर एक्सेस प्राप्त करें। +- **खरीद:** उत्पादन डिप्लॉयमेंट के लिए स्थायी लाइसेंस प्राप्त करें। + +## चरण‑दर‑चरण गाइड + +### चरण 1: कस्टम लॉगर क्लास परिभाषित करें (log warnings c#) +`ILogger` को लागू करने वाली क्लास बनाएं। यह क्लास त्रुटियों, चेतावनियों और सूचना संदेशों को कैप्चर करेगी। + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**व्याख्या:** `HasErrors` फ़्लैग आपको यह तय करने में मदद करता है कि प्रोसेसिंग जारी रखनी है या नहीं। ये तीन मेथड्स अधिकांश रिडैक्शन परिदृश्यों में आवश्यक तीन लॉग लेवल्स के अनुरूप हैं। + +### चरण 2: फ़ाइल पाथ तैयार करें और स्रोत दस्तावेज़ खोलें +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**यह क्यों महत्वपूर्ण है:** यूटिलिटी मेथड्स का उपयोग आपके कोड को साफ़ रखता है और यह सुनिश्चित करता है कि आउटपुट फ़ोल्डर मौजूद हो, इससे पहले कि आप **रिडैक्टेड दस्तावेज़ सहेजें**। + +### चरण 3: कस्टम लॉगर का उपयोग करते हुए रिडैक्शन लागू करें +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**व्याख्या:** +1. `Redactor` को `RedactorSettings(logger)` के साथ इंस्टैंशिएट किया जाता है, जिससे आपका `CustomLogger` जुड़ता है। +2. रिडैक्शन लागू करने के बाद, कोड `logger.HasErrors` की जाँच करता है। यदि कोई त्रुटि नहीं हुई, तो दस्तावेज़ सहेजा जाता है—जो **रिडैक्टेड दस्तावेज़ सहेजें** लॉजिक को रास्टराइज़ेशन के बिना दर्शाता है। + +### सामान्य कठिनाइयाँ और समस्या निवारण +- **लॉग आउटपुट गायब:** सुनिश्चित करें कि प्रत्येक `Log*` मेथड सही तरीके से ओवरराइड किया गया है। +- **फ़ाइल एक्सेस अपवाद:** सुनिश्चित करें कि एप्लिकेशन के पास स्रोत और आउटपुट पाथ दोनों के लिए पढ़ने/लिखने की अनुमति है। +- **लॉगर नहीं जुड़ा:** `RedactorSettings(logger)` पैरामीटर आवश्यक है; इसे छोड़ने से कस्टम लॉगिंग निष्क्रिय हो जाती है। + +## व्यावहारिक अनुप्रयोग +1. **अनुपालन रिपोर्टिंग:** ऑडिट ट्रेल्स के लिए लॉग एंट्रीज़ को CSV या डेटाबेस में एक्सपोर्ट करें। +2. **त्रुटि ट्रैकिंग:** `LogError` आउटपुट को स्कैन करके समस्याग्रस्त फ़ाइलें जल्दी ढूँढ़ें। +3. **वर्कफ़्लो ऑटोमेशन:** जब `LogWarning` कॉल किया जाए तो डाउनस्ट्रीम प्रोसेस (जैसे, अनुपालन अधिकारी को सूचित करना) ट्रिगर करें। + +## प्रदर्शन संबंधी विचार +- **स्ट्रीम्स को तुरंत डिस्पोज़ करें** ताकि मेमोरी मुक्त हो, विशेषकर बड़े बैच प्रोसेसिंग के समय। +- **CPU और मेमोरी की निगरानी** करें जब बड़े पैमाने पर रिडैक्शन हो; लॉगर सिंक्रोनाइज़ेशन का ध्यान रखते हुए समानांतर में दस्तावेज़ प्रोसेस करने पर विचार करें। +- **अपडेट रहें:** GroupDocs.Redaction के नए संस्करण अक्सर प्रदर्शन अनुकूलन और अतिरिक्त लॉगिंग हुक शामिल करते हैं। + +## निष्कर्ष +**कस्टम लॉगर c#** को लागू करके, आपको रिडैक्शन पाइपलाइन के हर चरण में विस्तृत अंतर्दृष्टि मिलती है, जिससे अनुपालन मानकों को पूरा करना और समस्याओं का डीबग करना आसान हो जाता है। यहाँ दिखाया गया तरीका GroupDocs.Redaction for .NET के साथ सहजता से काम करता है और इसे किसी भी .NET लॉगिंग फ्रेमवर्क के साथ एकीकृत किया जा सकता है जिसे आप पहले से उपयोग कर रहे हैं। + +--- + +## अक्सर पूछे जाने वाले प्रश्न + +**Q: GroupDocs.Redaction के साथ कस्टम लॉगिंग का उद्देश्य क्या है?** +A: कस्टम लॉगिंग अनुपालन, त्रुटि ट्रैकिंग और वर्कफ़्लो अनुकूलन के लिए रिडैक्शन को ट्रैक और प्रबंधित करने में मदद करती है। + +**Q: कस्टम लॉगर का उपयोग करके त्रुटियों को कैसे संभालें?** +A: अपने `CustomLogger` क्लास में `LogError` लागू करें; `HasErrors` फ़्लैग आवश्यक होने पर प्रोसेसिंग को रोकने की अनुमति देता है। + +**Q: क्या कस्टम लॉगिंग को अन्य सिस्टमों के साथ एकीकृत किया जा सकता है?** +A: हाँ, लॉगर मेथड्स को विस्तारित करके आप लॉग संदेशों को CRM, ERP या केंद्रीकृत मॉनिटरिंग टूल्स में फ़ॉरवर्ड कर सकते हैं। + +**Q: कस्टम लॉगिंग लागू करते समय सामान्य कठिनाइयाँ क्या हैं?** +A: गलत मेथड इम्प्लीमेंटेशन, `RedactorSettings(logger)` का अभाव, और फ़ाइल अनुमति समस्याएँ सबसे अधिक होती हैं। + +**Q: कस्टम लॉगिंग दस्तावेज़ रिडैक्शन वर्कफ़्लो को कैसे सुधारती है?** +A: विस्तृत लॉग रियल‑टाइम दृश्यता प्रदान करते हैं, समस्या निवारण को सरल बनाते हैं, और ऑडिट आवश्यकताओं को पूरा करते हैं। + +## संसाधन +- **डॉक्यूमेंटेशन:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API रेफ़रेंस:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **डाउनलोड:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**अंतिम अपडेट:** 2026-03-28 +**परीक्षण किया गया:** GroupDocs.Redaction 23.11 for .NET +**लेखक:** GroupDocs \ No newline at end of file diff --git a/content/hongkong/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/hongkong/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..262ec0de --- /dev/null +++ b/content/hongkong/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,178 @@ +--- +date: '2026-03-28' +description: 學習如何在 GroupDocs.Redaction for .NET 中使用 C# 實作自訂記錄器,啟用詳細的自訂日誌記錄,並更輕鬆地完成合規報告。 +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: 在 GroupDocs.Redaction for .NET 中實作自訂 C# 記錄器 +type: docs +url: /zh-hant/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# 在 GroupDocs.Redaction for .NET 中實作自訂 logger c# + +有效管理文件遮蔽至關重要,尤其在處理敏感資訊時。本指南將教您 **如何在 GroupDocs.Redaction for .NET 中實作自訂 logger c#**,讓您全面掌控記錄、錯誤處理與稽核追蹤。 + +## 快速答案 +- **自訂 logger c# 的作用是什麼?** 它會在遮蔽過程中捕獲錯誤、警告與資訊訊息。 +- **哪個函式庫提供 ILogger 介面?** GroupDocs.Redaction for .NET。 +- **我能在不進行光柵化的情況下儲存已遮蔽的文件嗎?** 可以 – 使用 `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`。 +- **生產環境使用是否需要授權?** 正式版授權是必需的;亦提供試用版供評估使用。 +- **此方法是否相容於 .NET Core / .NET 6+?** 完全相容 – 相同的 API 可在 .NET Framework 及 .NET Core/5/6 上運作。 + +## 什麼是自訂 logger c#? +**自訂 logger c#** 是一個實作 GroupDocs.Redaction 所提供的 `ILogger` 介面的類別。它讓您能將記錄訊息傳送至任意位置——如主控台、檔案、資料庫或外部監控系統——同時提供清晰的遮蔽工作流程檢視。 + +## 為何在 GroupDocs.Redaction 中使用自訂 .NET 記錄? +- **合規與稽核:** 詳細的記錄滿足法規要求。 +- **錯誤可見性:** `LogError` 與 `LogWarning` 可即時回饋問題。 +- **整合彈性:** 可將記錄轉發至現有的 .NET 記錄框架(Serilog、NLog 等)。 + +## 前置條件 +- 已安裝 **GroupDocs.Redaction for .NET**(請參閱以下安裝說明)。 +- .NET 開發環境(Visual Studio、VS Code 或 CLI)。 +- 基本的 C# 知識與檔案串流使用經驗。 + +## 安裝 + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +搜尋 **"GroupDocs.Redaction"** 並安裝最新版本。 + +## 取得授權 +- **免費試用:** 使用臨時授權測試 API。 +- **臨時授權:** 在有限期間內取得完整功能。 +- **購買:** 獲得永久授權以供正式部署使用。 + +## 步驟指南 + +### 步驟 1:定義自訂 logger 類別(log warnings c#) +建立一個實作 `ILogger` 的類別。此類別會捕獲錯誤、警告與資訊訊息。 + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**說明:** `HasErrors` 旗標可協助您判斷是否繼續處理。這三個方法對應於大多數遮蔽情境中所需的三種記錄層級。 + +### 步驟 2:準備檔案路徑並開啟來源文件 +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**為何重要:** 使用工具方法可讓程式碼保持整潔,且在嘗試 **儲存已遮蔽文件** 前確保輸出資料夾已存在。 + +### 步驟 3:套用遮蔽同時使用自訂 logger +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**說明:** +1. 透過 `RedactorSettings(logger)` 建立 `Redactor` 實例,將您的 `CustomLogger` 連結進去。 +2. 套用遮蔽後,程式會檢查 `logger.HasErrors`。若未發生錯誤,則儲存文件——示範了在不進行光柵化的情況下 **儲存已遮蔽文件** 的邏輯。 + +### 常見陷阱與故障排除 +- **缺少記錄輸出:** 確認每個 `Log*` 方法皆正確覆寫。 +- **檔案存取例外:** 確保應用程式對來源與輸出路徑皆具有讀寫權限。 +- **Logger 未正確連接:** `RedactorSettings(logger)` 參數是必要的,若省略則會停用自訂記錄。 + +## 實務應用 +1. **合規報告:** 將記錄條目匯出為 CSV 或資料庫,以供稽核追蹤。 +2. **錯誤追蹤:** 透過掃描 `LogError` 輸出快速定位問題檔案。 +3. **工作流程自動化:** 當呼叫 `LogWarning` 時觸發後續流程(例如通知合規主管)。 + +## 效能考量 +- **即時釋放串流** 以釋放記憶體,特別是在處理大量批次時。 +- **監控 CPU 與記憶體** 使用情況於大量遮蔽時;可考慮平行處理文件,同時謹慎同步 logger。 +- **保持更新:** 新版 GroupDocs.Redaction 常包含效能優化與額外的記錄掛鉤。 + +## 結論 +透過實作 **custom logger c#**,您能深入了解遮蔽流程的每個步驟,從而更輕鬆符合合規標準與除錯。此方法與 GroupDocs.Redaction for .NET 完美結合,且可擴充以整合您已使用的任何 .NET 記錄框架。 + +--- + +## 常見問答 + +**Q: 使用 GroupDocs.Redaction 的自訂記錄目的為何?** +A: 自訂記錄有助於追蹤與管理遮蔽,以符合合規、錯誤追蹤與工作流程最佳化。 + +**Q: 如何使用自訂 logger 處理錯誤?** +A: 在 `CustomLogger` 類別中實作 `LogError`;`HasErrors` 旗標可在需要時中止處理。 + +**Q: 自訂記錄能否與其他系統整合?** +A: 可以,透過擴充 logger 方法,將記錄訊息轉發至 CRM、ERP 或集中監控工具。 + +**Q: 實作自訂記錄時常見的陷阱有哪些?** +A: 方法實作錯誤、缺少 `RedactorSettings(logger)`,以及檔案權限問題是最常見的。 + +**Q: 自訂記錄如何提升文件遮蔽工作流程?** +A: 詳細的記錄提供即時可視性、簡化除錯,並滿足稽核需求。 + +## 資源 +- **文件說明:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API 參考:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **下載:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**最後更新:** 2026-03-28 +**測試環境:** GroupDocs.Redaction 23.11 for .NET +**作者:** GroupDocs + +--- \ No newline at end of file diff --git a/content/hungarian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/hungarian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..eb30a44b --- /dev/null +++ b/content/hungarian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,183 @@ +--- +date: '2026-03-28' +description: Tanulja meg, hogyan valósíthat meg egy egyedi naplózót C#-ban a GroupDocs.Redaction + for .NET-ben, amely részletes egyedi naplózást tesz lehetővé .NET környezetben, + és megkönnyíti a megfelelőségi jelentést. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Egyedi naplózó implementálása C#-ban a GroupDocs.Redaction .NET-hez +type: docs +url: /hu/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Egyéni naplózó c# implementálása a GroupDocs.Redaction .NET-hez + +A dokumentumok redakciójának hatékony kezelése kritikus, különösen érzékeny információk kezelésekor. Ebben az útmutatóban megtanulja, **hogyan kell egy egyéni naplózót c#-ban implementálni** a GroupDocs.Redaction .NET-hez, amely teljes ellenőrzést biztosít a naplózás, hibakezelés és audit nyomvonalak felett. + +## Gyors válaszok +- **Mit csinál egy egyéni naplózó c#?** Hibákat, figyelmeztetéseket és információs üzeneteket rögzít a redakció során. +- **Melyik könyvtár biztosítja az ILogger interfészt?** GroupDocs.Redaction for .NET. +- **Menthetem a redakciózott dokumentumot rasterizáció nélkül?** Igen – használja a `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })` kódot. +- **Szükségem van licencre a termeléshez?** Teljes licenc szükséges a termeléshez; próba verzió elérhető értékeléshez. +- **Ez a megközelítés kompatibilis a .NET Core / .NET 6+ verziókkal?** Teljesen – ugyanaz az API működik a .NET Framework és a .NET Core/5/6 között. + +## Mi az egyéni naplózó c#? +A **custom logger c#** egy olyan osztály, amely megvalósítja a GroupDocs.Redaction által biztosított `ILogger` interfészt. Lehetővé teszi, hogy a naplóüzeneteket bárhová irányítsa – konzolra, fájlba, adatbázisba vagy külső felügyeleti rendszerekbe – miközben átlátható képet ad a redakció munkafolyamatáról. + +## Miért használjunk egyéni naplózást .net-ben a GroupDocs.Redaction-nél? +- **Megfelelés és auditálás:** A részletes naplók megfelelnek a szabályozási követelményeknek. +- **Hibák láthatósága:** A `LogError` és `LogWarning` azonnali visszajelzést ad a problémákról. +- **Integrációs rugalmasság:** A naplókat továbbíthatja meglévő .NET naplózási keretrendszerekbe (Serilog, NLog, stb.). + +## Előfeltételek +- **GroupDocs.Redaction for .NET** telepítve (lásd a telepítést alább). +- .NET fejlesztői környezet (Visual Studio, VS Code vagy CLI). +- Alap C# ismeretek és fájlfolyamok ismerete. + +## Telepítés + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Keresse meg a **"GroupDocs.Redaction"**-t és telepítse a legújabb verziót. + +## Licenc megszerzése +- **Ingyenes próba:** Tesztelje az API-t egy ideiglenes licenccel. +- **Ideiglenes licenc:** Teljes funkcióhozzáférést kap korlátozott időre. +- **Vásárlás:** Szerezzen örökös licencet a termelési telepítésekhez. + +## Lépésről‑lépésre útmutató + +### 1. lépés: Egyéni naplózó osztály definiálása (log warnings c#) + +Hozzon létre egy osztályt, amely megvalósítja az `ILogger`-t. Ez az osztály hibákat, figyelmeztetéseket és információs üzeneteket rögzít. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Magyarázat:** A `HasErrors` jelző segít eldönteni, hogy folytassa-e a feldolgozást. A három metódus a legtöbb redakciós forgatókönyvhöz szükséges három naplózási szintnek felel meg. + +### 2. lépés: Fájlútvonalak előkészítése és a forrásdokumentum megnyitása + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Miért fontos:** Az segédmetódusok használata tisztán tartja a kódot, és biztosítja, hogy a kimeneti mappa létezzen, mielőtt a **redakciózott dokumentum mentését** megpróbálná. + +### 3. lépés: Redakciók alkalmazása az egyéni naplózó használatával + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Magyarázat:** +1. A `Redactor` a `RedactorSettings(logger)`-rel van példányosítva, ami összekapcsolja az `CustomLogger`-t. +2. Redakció alkalmazása után a kód ellenőrzi a `logger.HasErrors` értékét. Ha nincs hiba, a dokumentum mentésre kerül – bemutatva a **redakciózott dokumentum mentése** logikát rasterizáció nélkül. + +### Gyakori hibák és hibaelhárítás +- **Hiányzó napló kimenet:** Ellenőrizze, hogy minden `Log*` metódus helyesen felül van-e definiálva. +- **Fájlhozzáférési kivételek:** Győződjön meg róla, hogy az alkalmazásnak olvasási/írási jogosultsága van a forrás- és kimeneti útvonalakhoz. +- **A naplózó nincs csatlakoztatva:** A `RedactorSettings(logger)` paraméter elengedhetetlen; elhagyása letiltja az egyéni naplózást. + +## Gyakorlati alkalmazások +1. **Megfelelőségi jelentés:** Exportálja a naplóbejegyzéseket CSV-be vagy adatbázisba audit nyomvonalakhoz. +2. **Hibakövetés:** Gyorsan megtalálja a problémás fájlokat a `LogError` kimenet átvizsgálásával. +3. **Munkafolyamat automatizálás:** Indítson el downstream folyamatokat (pl. értesítse a megfelelőségi felelőst), amikor a `LogWarning` meghívásra kerül. + +## Teljesítmény szempontok +- **Az adatfolyamok gyors elengedése** a memória felszabadításához, különösen nagy kötegek feldolgozásakor. +- **CPU és memória monitorozása** tömeges redakciók során; fontolja meg a dokumentumok párhuzamos feldolgozását a naplózó szinkronizációra ügyelve. +- **Legyen naprakész:** A GroupDocs.Redaction újabb verziói gyakran tartalmaznak teljesítményoptimalizációkat és további naplózási horgokat. + +## Következtetés + +A **custom logger c#** implementálásával részletes betekintést nyer a redakciós folyamat minden lépésébe, ami megkönnyíti a megfelelőségi szabványok betartását és a hibák hibakeresését. Az itt bemutatott megközelítés zökkenőmentesen működik a GroupDocs.Redaction for .NET‑nel, és kiterjeszthető bármely meglévő .NET naplózási keretrendszerrel. + +--- + +## Gyakran Ismételt Kérdések + +**Q: Mi a célja az egyéni naplózásnak a GroupDocs.Redaction-nél?** +A: Az egyéni naplózás segít nyomon követni és kezelni a redakciókat a megfelelőség, hibakövetés és munkafolyamat optimalizálás érdekében. + +**Q: Hogyan kezeljem a hibákat egy egyéni naplózóval?** +A: Implementálja a `LogError`-t a `CustomLogger` osztályában; a `HasErrors` jelző lehetővé teszi a feldolgozás leállítását, ha szükséges. + +**Q: Integrálható az egyéni naplózás más rendszerekkel?** +A: Igen, a naplóüzeneteket továbbíthatja CRM, ERP vagy központosított felügyeleti eszközök felé a naplózó metódusok kibővítésével. + +**Q: Melyek a leggyakoribb hibák az egyéni naplózás implementálásakor?** +A: A helytelen metódusimplementációk, a hiányzó `RedactorSettings(logger)`, és a fájlengedélyek problémái a leggyakoribbak. + +**Q: Hogyan javítja az egyéni naplózás a dokumentum redakciós munkafolyamatokat?** +A: A részletes naplók valós idejű láthatóságot biztosítanak, egyszerűsítik a hibaelhárítást, és megfelelnek az audit követelményeknek. + +## Források + +- **Dokumentáció:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API referencia:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Letöltés:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Legutóbb frissítve:** 2026-03-28 +**Tesztelve ezzel:** GroupDocs.Redaction 23.11 for .NET +**Szerző:** GroupDocs \ No newline at end of file diff --git a/content/indonesian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/indonesian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..52172b1e --- /dev/null +++ b/content/indonesian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,185 @@ +--- +date: '2026-03-28' +description: Pelajari cara mengimplementasikan logger khusus C# di GroupDocs.Redaction + untuk .NET, memungkinkan pencatatan khusus yang detail di .NET dan pelaporan kepatuhan + yang lebih mudah. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Menerapkan logger khusus C# di GroupDocs.Redaction untuk .NET +type: docs +url: /id/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Implement logger khusus c# di GroupDocs.Redaction untuk .NET + +Mengelola redaksi dokumen secara efisien sangat penting, terutama saat menangani informasi sensitif. Dalam panduan ini Anda akan belajar **cara mengimplementasikan logger khusus c#** dengan GroupDocs.Redaction untuk .NET, memberi Anda kontrol penuh atas pencatatan, penanganan kesalahan, dan jejak audit. + +## Jawaban Cepat +- **Apa yang dilakukan logger khusus c#?** Ia menangkap kesalahan, peringatan, dan pesan informasional selama proses redaksi. +- **Perpustakaan mana yang menyediakan antarmuka ILogger?** GroupDocs.Redaction untuk .NET. +- **Bisakah saya menyimpan dokumen yang telah direduksi tanpa rasterisasi?** Ya – gunakan `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Apakah saya memerlukan lisensi untuk penggunaan produksi?** Lisensi penuh diperlukan untuk produksi; versi percobaan tersedia untuk evaluasi. +- **Apakah pendekatan ini kompatibel dengan .NET Core / .NET 6+?** Tentu – API yang sama berfungsi di .NET Framework dan .NET Core/5/6. + +## Apa itu logger khusus c#? +Sebuah **logger khusus c#** adalah kelas yang mengimplementasikan antarmuka `ILogger` yang disediakan oleh GroupDocs.Redaction. Ini memungkinkan Anda mengarahkan pesan log ke mana saja yang Anda butuhkan—konsol, file, basis data, atau sistem pemantauan eksternal—sementara memberikan pandangan yang jelas tentang alur kerja redaksi. + +## Mengapa menggunakan pencatatan khusus .net dengan GroupDocs.Redaction? +- **Kepatuhan & Audit:** Log terperinci memenuhi persyaratan regulasi. +- **Visibilitas Kesalahan:** `LogError` dan `LogWarning` memberikan umpan balik langsung tentang masalah. +- **Fleksibilitas Integrasi:** Meneruskan log ke kerangka kerja pencatatan .NET yang ada (Serilog, NLog, dll.). + +## Prasyarat +- **GroupDocs.Redaction untuk .NET** terpasang (lihat instalasi di bawah). +- Lingkungan pengembangan .NET (Visual Studio, VS Code, atau CLI). +- Pengetahuan dasar C# dan familiaritas dengan aliran file. + +## Instalasi + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Cari **"GroupDocs.Redaction"** dan instal versi terbaru. + +## Akuisisi Lisensi +- **Uji Coba Gratis:** Uji API dengan lisensi sementara. +- **Lisensi Sementara:** Dapatkan akses penuh ke fitur untuk periode terbatas. +- **Pembelian:** Dapatkan lisensi permanen untuk penyebaran produksi. + +## Panduan Langkah‑per‑Langkah + +### Langkah 1: Definisikan kelas logger khusus (log peringatan c#) + +Buat kelas yang mengimplementasikan `ILogger`. Kelas ini akan menangkap kesalahan, peringatan, dan pesan informasional. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Penjelasan:** Flag `HasErrors` membantu Anda memutuskan apakah akan melanjutkan pemrosesan. Tiga metode tersebut sesuai dengan tiga level log yang Anda perlukan dalam kebanyakan skenario redaksi. + +### Langkah 2: Siapkan jalur file dan buka dokumen sumber + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Mengapa ini penting:** Menggunakan metode utilitas menjaga kode Anda tetap bersih dan memastikan folder output ada sebelum Anda mencoba **menyimpan dokumen yang direduksi**. + +### Langkah 3: Terapkan redaksi sambil menggunakan logger khusus + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Penjelasan:** +1. `Redactor` diinstansiasi dengan `RedactorSettings(logger)`, menghubungkan `CustomLogger` Anda. +2. Setelah menerapkan redaksi, kode memeriksa `logger.HasErrors`. Jika tidak ada kesalahan, dokumen disimpan—menunjukkan logika **menyimpan dokumen yang direduksi** tanpa rasterisasi. + +### Kesulitan Umum & Pemecahan Masalah +- **Output log hilang:** Verifikasi bahwa setiap metode `Log*` telah ditimpa dengan benar. +- **Pengecualian akses file:** Pastikan aplikasi memiliki izin baca/tulis untuk jalur sumber dan output. +- **Logger tidak terhubung:** Parameter `RedactorSettings(logger)` penting; menghilangkannya menonaktifkan pencatatan khusus. + +## Aplikasi Praktis +1. **Pelaporan Kepatuhan:** Ekspor entri log ke CSV atau basis data untuk jejak audit. +2. **Pelacakan Kesalahan:** Cepat temukan file bermasalah dengan memindai output `LogError`. +3. **Otomatisasi Alur Kerja:** Memicu proses hilir (mis., memberi tahu petugas kepatuhan) ketika `LogWarning` dipanggil. + +## Pertimbangan Kinerja +- **Segera tutup stream** untuk membebaskan memori, terutama saat memproses batch besar. +- **Pantau CPU & memori** selama redaksi massal; pertimbangkan memproses dokumen secara paralel dengan sinkronisasi logger yang hati-hati. +- **Tetap diperbarui:** Versi terbaru GroupDocs.Redaction sering menyertakan optimasi kinerja dan hook pencatatan tambahan. + +## Kesimpulan + +Dengan mengimplementasikan **logger khusus c#**, Anda memperoleh wawasan terperinci pada setiap langkah pipeline redaksi, memudahkan pemenuhan standar kepatuhan dan debugging masalah. Pendekatan yang ditunjukkan di sini bekerja mulus dengan GroupDocs.Redaction untuk .NET dan dapat diperluas untuk terintegrasi dengan kerangka kerja pencatatan .NET apa pun yang sudah Anda gunakan. + +--- + +## Pertanyaan yang Sering Diajukan + +**Q: Apa tujuan pencatatan khusus dengan GroupDocs.Redaction?** +A: Pencatatan khusus membantu melacak dan mengelola redaksi untuk kepatuhan, pelacakan kesalahan, dan optimasi alur kerja. + +**Q: Bagaimana cara menangani kesalahan menggunakan logger khusus?** +A: Implementasikan `LogError` dalam kelas `CustomLogger` Anda; flag `HasErrors` memungkinkan Anda menghentikan pemrosesan jika diperlukan. + +**Q: Bisakah pencatatan khusus diintegrasikan dengan sistem lain?** +A: Ya, Anda dapat meneruskan pesan log ke CRM, ERP, atau alat pemantauan terpusat dengan memperluas metode logger. + +**Q: Apa saja kesulitan umum saat mengimplementasikan pencatatan khusus?** +A: Implementasi metode yang salah, kehilangan `RedactorSettings(logger)`, dan masalah izin file adalah yang paling sering. + +**Q: Bagaimana pencatatan khusus meningkatkan alur kerja redaksi dokumen?** +A: Log terperinci memberikan visibilitas waktu nyata, menyederhanakan pemecahan masalah, dan memenuhi persyaratan audit. + +## Sumber Daya + +- **Dokumentasi:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **Referensi API:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Unduh:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Terakhir Diperbarui:** 2026-03-28 +**Diuji Dengan:** GroupDocs.Redaction 23.11 untuk .NET +**Penulis:** GroupDocs + +--- \ No newline at end of file diff --git a/content/italian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/italian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..17735310 --- /dev/null +++ b/content/italian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,186 @@ +--- +date: '2026-03-28' +description: Scopri come implementare un logger personalizzato in C# in GroupDocs.Redaction + per .NET, abilitando una registrazione dettagliata personalizzata in .NET e una + più semplice generazione di report di conformità. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Implementare un logger personalizzato C# in GroupDocs.Redaction per .NET +type: docs +url: /it/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Implementa logger personalizzato c# in GroupDocs.Redaction per .NET + +Gestire le redazioni dei documenti in modo efficiente è fondamentale, soprattutto quando si trattano informazioni sensibili. In questa guida imparerai **come implementare un custom logger c#** con GroupDocs.Redaction per .NET, ottenendo il pieno controllo su logging, gestione degli errori e tracciamento degli audit. + +## Risposte rapide +- **Cosa fa un custom logger c#?** Cattura errori, avvisi e messaggi informativi durante la redazione. +- **Quale libreria fornisce l'interfaccia ILogger?** GroupDocs.Redaction per .NET. +- **Posso salvare il documento redatto senza rasterizzazione?** Sì – usa `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **È necessaria una licenza per l'uso in produzione?** È richiesta una licenza completa per la produzione; è disponibile una versione di prova per la valutazione. +- **Questo approccio è compatibile con .NET Core / .NET 6+?** Assolutamente – la stessa API funziona su .NET Framework e .NET Core/5/6. + +## Cos'è un custom logger c#? +Un **custom logger c#** è una classe che implementa l'interfaccia `ILogger` fornita da GroupDocs.Redaction. Ti consente di indirizzare i messaggi di log dove necessario—console, file, database o sistemi di monitoraggio esterni—offrendoti una visione chiara del flusso di lavoro di redazione. + +## Perché utilizzare il logging personalizzato .net con GroupDocs.Redaction? +- **Conformità e audit:** Log dettagliati soddisfano i requisiti normativi. +- **Visibilità degli errori:** `LogError` e `LogWarning` forniscono feedback immediato sui problemi. +- **Flessibilità di integrazione:** Inoltra i log ai framework di logging .NET esistenti (Serilog, NLog, ecc.). + +## Prerequisiti +- **GroupDocs.Redaction per .NET** installato (vedi installazione sotto). +- Un ambiente di sviluppo .NET (Visual Studio, VS Code o CLI). +- Conoscenza di base di C# e familiarità con gli stream di file. + +## Installazione + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Cerca **"GroupDocs.Redaction"** e installa l'ultima versione. + +## Acquisizione licenza +- **Versione di prova gratuita:** Testa l'API con una licenza temporanea. +- **Licenza temporanea:** Ottieni l'accesso a tutte le funzionalità per un periodo limitato. +- **Acquisto:** Ottieni una licenza perpetua per le distribuzioni in produzione. + +## Guida passo‑passo + +### Passo 1: Definisci una classe custom logger (log warnings c#) + +Crea una classe che implementa `ILogger`. Questa classe catturerà errori, avvisi e messaggi informativi. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Spiegazione:** Il flag `HasErrors` ti aiuta a decidere se continuare l'elaborazione. I tre metodi corrispondono ai tre livelli di log di cui avrai bisogno nella maggior parte degli scenari di redazione. + +### Passo 2: Prepara i percorsi dei file e apri il documento sorgente + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Perché è importante:** L'uso di metodi di utilità mantiene il codice pulito e garantisce che la cartella di output esista prima di tentare di **salvare il documento redatto**. + +### Passo 3: Applica le redazioni utilizzando il custom logger + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Spiegazione:** +1. Il `Redactor` viene istanziato con `RedactorSettings(logger)`, collegando il tuo `CustomLogger`. +2. Dopo aver applicato una redazione, il codice verifica `logger.HasErrors`. Se non si sono verificati errori, il documento viene salvato—dimostrando la logica di **salvare il documento redatto** senza rasterizzazione. + +### Problemi comuni e risoluzione + +- **Output di log mancante:** Verifica che ogni metodo `Log*` sia correttamente sovrascritto. +- **Eccezioni di accesso al file:** Assicurati che l'applicazione abbia i permessi di lettura/scrittura sia per i percorsi di origine che di output. +- **Logger non collegato:** Il parametro `RedactorSettings(logger)` è essenziale; ometterlo disabilita il logging personalizzato. + +## Applicazioni pratiche + +1. **Report di conformità:** Esporta le voci di log in CSV o database per i tracciati di audit. +2. **Tracciamento degli errori:** Individua rapidamente i file problematici scansionando l'output di `LogError`. +3. **Automazione del flusso di lavoro:** Attiva processi a valle (ad es., notificare un responsabile della conformità) quando viene invocato `LogWarning`. + +## Considerazioni sulle prestazioni + +- **Chiudi gli stream prontamente** per liberare memoria, specialmente durante l'elaborazione di grandi lotti. +- **Monitora CPU e memoria** durante le redazioni massive; considera l'elaborazione dei documenti in parallelo con una sincronizzazione attenta del logger. +- **Rimani aggiornato:** Le versioni più recenti di GroupDocs.Redaction includono spesso ottimizzazioni delle prestazioni e hook di logging aggiuntivi. + +## Conclusione + +Implementando un **custom logger c#**, ottieni una visione granulare di ogni fase della pipeline di redazione, facilitando il rispetto degli standard di conformità e il debug dei problemi. L'approccio mostrato qui funziona senza problemi con GroupDocs.Redaction per .NET e può essere esteso per integrarsi con qualsiasi framework di logging .NET che utilizzi già. + +--- + +## Domande frequenti + +**D: Qual è lo scopo del logging personalizzato con GroupDocs.Redaction?** +R: Il logging personalizzato aiuta a tracciare e gestire le redazioni per la conformità, il tracciamento degli errori e l'ottimizzazione del flusso di lavoro. + +**D: Come gestisco gli errori usando un custom logger?** +R: Implementa `LogError` nella tua classe `CustomLogger`; il flag `HasErrors` ti consente di interrompere l'elaborazione se necessario. + +**D: Il logging personalizzato può essere integrato con altri sistemi?** +R: Sì, puoi inoltrare i messaggi di log a CRM, ERP o strumenti di monitoraggio centralizzati estendendo i metodi del logger. + +**D: Quali sono alcuni errori comuni nell'implementare il logging personalizzato?** +R: Implementazioni errate dei metodi, mancanza di `RedactorSettings(logger)` e problemi di permessi sui file sono i più frequenti. + +**D: In che modo il logging personalizzato migliora i flussi di lavoro di redazione dei documenti?** +R: Log dettagliati forniscono visibilità in tempo reale, semplificano il troubleshooting e soddisfano i requisiti di audit. + +## Risorse + +- **Documentazione:** [Documentazione GroupDocs.Redaction .NET](https://docs.groupdocs.com/redaction/net/) +- **Riferimento API:** [Riferimento API GroupDocs.Redaction](https://reference.groupdocs.com/redaction/net) +- **Download:** [Download GroupDocs.Redaction per .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Ultimo aggiornamento:** 2026-03-28 +**Testato con:** GroupDocs.Redaction 23.11 per .NET +**Autore:** GroupDocs \ No newline at end of file diff --git a/content/japanese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/japanese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..36224681 --- /dev/null +++ b/content/japanese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,178 @@ +--- +date: '2026-03-28' +description: GroupDocs.Redaction for .NETでカスタムロガー(C#)を実装する方法を学び、詳細なカスタムロギングとコンプライアンスレポートの作成を容易にします。 +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: .NET 用 GroupDocs.Redaction でカスタムロガー C# を実装する +type: docs +url: /ja/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# GroupDocs.Redaction for .NET でカスタムロガー C# を実装する + +文書の赤字処理を効率的に管理することは重要です、特に機密情報を扱う場合はなおさらです。このガイドでは、GroupDocs.Redaction for .NET を使用して **カスタムロガー C# の実装方法** を学び、ロギング、エラーハンドリング、監査トレイルを完全に制御できるようにします。 + +## クイック回答 +- **カスタムロガー C# は何をしますか?** 赤字処理中にエラー、警告、情報メッセージをキャプチャします。 +- **ILogger インターフェイスを提供するライブラリはどれですか?** GroupDocs.Redaction for .NET。 +- **ラスタライズせずに赤字処理された文書を保存できますか?** はい – `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })` を使用します。 +- **本番環境で使用するにはライセンスが必要ですか?** 本番環境ではフルライセンスが必要です。評価用にトライアルが利用可能です。 +- **このアプローチは .NET Core / .NET 6+ と互換性がありますか?** もちろんです – 同じ API が .NET Framework と .NET Core/5/6 で動作します。 + +## カスタムロガー C# とは? +**カスタムロガー C#** は、GroupDocs.Redaction が提供する `ILogger` インターフェイスを実装したクラスです。コンソール、ファイル、データベース、外部監視システムなど、必要な場所へログメッセージをルーティングでき、赤字処理ワークフローを明確に把握できます。 + +## GroupDocs.Redaction でカスタムロギング .NET を使用する理由 +- **コンプライアンスと監査:** 詳細なログは規制要件を満たします。 +- **エラーの可視性:** `LogError` と `LogWarning` は問題に対する即時フィードバックを提供します。 +- **統合の柔軟性:** 既存の .NET ロギングフレームワーク(Serilog、NLog など)へログを転送できます。 + +## 前提条件 +- **GroupDocs.Redaction for .NET** がインストールされていること(下記インストール手順を参照)。 +- .NET 開発環境(Visual Studio、VS Code、または CLI)。 +- 基本的な C# の知識とファイルストリームの理解。 + +## インストール + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**パッケージマネージャー** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet パッケージマネージャー UI** +**"GroupDocs.Redaction"** を検索し、最新バージョンをインストールしてください。 + +## ライセンス取得 +- **無料トライアル:** 一時的なライセンスで API をテストします。 +- **一時ライセンス:** 限定期間でフル機能にアクセスできます。 +- **購入:** 本番展開用の永続ライセンスを取得します。 + +## ステップバイステップガイド + +### 手順 1: カスタムロガークラスを定義する(警告ログ C#) +`ILogger` を実装するクラスを作成します。このクラスはエラー、警告、情報メッセージをキャプチャします。 + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**説明:** `HasErrors` フラグは処理を継続するかどうかの判断に役立ちます。3 つのメソッドは、ほとんどの赤字処理シナリオで必要となる 3 つのログレベルに対応しています。 + +### 手順 2: ファイルパスを準備し、ソース文書を開く +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**重要性:** ユーティリティメソッドを使用するとコードが整理され、**赤字処理された文書を保存**する前に出力フォルダーが存在することが保証されます。 + +### 手順 3: カスタムロガーを使用して赤字処理を適用する +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**説明:** +1. `Redactor` は `RedactorSettings(logger)` でインスタンス化され、`CustomLogger` と連携します。 +2. 赤字処理を適用した後、コードは `logger.HasErrors` をチェックします。エラーがなければ文書が保存され、ラスタライズなしで **赤字処理された文書を保存** するロジックを示しています。 + +### 一般的な落とし穴とトラブルシューティング +- **ログ出力がない:** 各 `Log*` メソッドが正しくオーバーライドされているか確認してください。 +- **ファイルアクセス例外:** アプリケーションがソースと出力パスの両方に対して読み取り/書き込み権限を持っていることを確認してください。 +- **ロガーが接続されていない:** `RedactorSettings(logger)` パラメータは必須です。省略するとカスタムロギングが無効になります。 + +## 実用的な応用例 +1. **コンプライアンスレポート:** ログエントリを CSV またはデータベースにエクスポートして監査トレイルを作成します。 +2. **エラートラッキング:** `LogError` 出力をスキャンして問題のあるファイルを迅速に特定します。 +3. **ワークフロー自動化:** `LogWarning` が呼び出されたときに、下流プロセス(例: コンプライアンス担当者への通知)をトリガーします。 + +## パフォーマンス上の考慮点 +- **ストリームを速やかに破棄** してメモリを解放します。特に大量バッチ処理時に重要です。 +- **CPU とメモリを監視** しながら大量の赤字処理を行います。ロガーの同期に注意しつつ、並列処理を検討してください。 +- **最新情報を入手:** GroupDocs.Redaction の新しいバージョンは、パフォーマンス最適化や追加のロギングフックが含まれることが多いです。 + +## 結論 +**カスタムロガー C#** を実装することで、赤字処理パイプラインの各ステップを細かく把握でき、コンプライアンス基準の遵守や問題のデバッグが容易になります。このアプローチは GroupDocs.Redaction for .NET とシームレスに連携し、既存の任意の .NET ロギングフレームワークと統合するよう拡張可能です。 + +--- + +## よくある質問 + +**Q: GroupDocs.Redaction でカスタムロギングを行う目的は何ですか?** +A: カスタムロギングは、コンプライアンス、エラートラッキング、ワークフロー最適化のために赤字処理を追跡・管理するのに役立ちます。 + +**Q: カスタムロガーでエラーを処理するにはどうすればよいですか?** +A: `CustomLogger` クラスで `LogError` を実装します。`HasErrors` フラグにより、必要に応じて処理を中止できます。 + +**Q: カスタムロギングを他のシステムと統合できますか?** +A: はい、ロガーメソッドを拡張することで、CRM、ERP、または集中監視ツールにログメッセージを転送できます。 + +**Q: カスタムロギング実装時の一般的な落とし穴は何ですか?** +A: メソッド実装の誤り、`RedactorSettings(logger)` の欠如、ファイル権限の問題が最も頻繁に発生します。 + +**Q: カスタムロギングは文書の赤字処理ワークフローをどのように改善しますか?** +A: 詳細なログはリアルタイムの可視性を提供し、トラブルシューティングを簡素化し、監査要件を満たします。 + +## リソース +- **ドキュメンテーション:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API リファレンス:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **ダウンロード:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**最終更新日:** 2026-03-28 +**テスト環境:** GroupDocs.Redaction 23.11 for .NET +**作者:** GroupDocs + +--- \ No newline at end of file diff --git a/content/korean/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/korean/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..d36f8d98 --- /dev/null +++ b/content/korean/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,178 @@ +--- +date: '2026-03-28' +description: GroupDocs.Redaction for .NET에서 C# 맞춤 로거를 구현하는 방법을 배우고, 상세한 맞춤 로깅과 보다 + 쉬운 규정 준수 보고를 가능하게 합니다. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: GroupDocs.Redaction for .NET에서 C# 사용자 정의 로거 구현 +type: docs +url: /ko/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# GroupDocs.Redaction for .NET에서 사용자 정의 로거 c# 구현 + +문서 레드액션을 효율적으로 관리하는 것은 특히 민감한 정보를 다룰 때 중요합니다. 이 가이드에서는 GroupDocs.Redaction for .NET과 함께 **custom logger c#를 구현하는 방법**을 배우게 되며, 로깅, 오류 처리 및 감사 추적에 대한 완전한 제어를 제공합니다. + +## 빠른 답변 +- **custom logger c#는 무엇을 하나요?** 레드액션 중 오류, 경고 및 정보 메시지를 캡처합니다. +- **ILogger 인터페이스를 제공하는 라이브러리는?** GroupDocs.Redaction for .NET. +- **레드액션된 문서를 래스터화 없이 저장할 수 있나요?** 예 – `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`를 사용합니다. +- **프로덕션 사용에 라이선스가 필요합니까?** 프로덕션에는 정식 라이선스가 필요하며, 평가용 트라이얼을 사용할 수 있습니다. +- **이 접근 방식이 .NET Core / .NET 6+와 호환되나요?** 물론입니다 – 동일한 API가 .NET Framework와 .NET Core/5/6 모두에서 작동합니다. + +## custom logger c#란 무엇인가? +**custom logger c#**는 GroupDocs.Redaction에서 제공하는 `ILogger` 인터페이스를 구현하는 클래스입니다. 콘솔, 파일, 데이터베이스 또는 외부 모니터링 시스템 등 필요한 곳으로 로그 메시지를 전달할 수 있으며, 레드액션 워크플로우를 명확히 파악할 수 있게 해줍니다. + +## GroupDocs.Redaction와 함께 custom logging .net을 사용하는 이유? +- **규정 준수 및 감사:** 상세 로그가 규제 요구사항을 충족합니다. +- **오류 가시성:** `LogError`와 `LogWarning`은 문제에 대한 즉각적인 피드백을 제공합니다. +- **통합 유연성:** 기존 .NET 로깅 프레임워크(Serilog, NLog 등)로 로그를 전달할 수 있습니다. + +## 사전 요구 사항 +- **GroupDocs.Redaction for .NET**이 설치되어 있음(아래 설치 섹션 참고). +- .NET 개발 환경(Visual Studio, VS Code 또는 CLI). +- 기본 C# 지식 및 파일 스트림에 대한 이해. + +## 설치 + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +**"GroupDocs.Redaction"**을 검색하고 최신 버전을 설치합니다. + +## 라이선스 획득 +- **무료 체험:** 임시 라이선스로 API를 테스트합니다. +- **임시 라이선스:** 제한된 기간 동안 전체 기능에 접근합니다. +- **구매:** 프로덕션 배포를 위한 영구 라이선스를 획득합니다. + +## 단계별 가이드 + +### 1단계: 사용자 정의 로거 클래스 정의 (log warnings c#) +`ILogger`를 구현하는 클래스를 생성합니다. 이 클래스는 오류, 경고 및 정보 메시지를 캡처합니다. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**설명:** `HasErrors` 플래그는 처리를 계속할지 여부를 결정하는 데 도움이 됩니다. 세 메서드는 대부분의 레드액션 시나리오에서 필요한 세 가지 로그 레벨에 해당합니다. + +### 2단계: 파일 경로 준비 및 원본 문서 열기 +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**왜 중요한가:** 유틸리티 메서드를 사용하면 코드가 깔끔해지고, **레드액션된 문서 저장**을 시도하기 전에 출력 폴더가 존재하는지 확인할 수 있습니다. + +### 3단계: 사용자 정의 로거를 사용하여 레드액션 적용 +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**설명:** +1. `Redactor`는 `RedactorSettings(logger)`로 인스턴스화되어 `CustomLogger`와 연결됩니다. +2. 레드액션을 적용한 후 코드가 `logger.HasErrors`를 확인합니다. 오류가 없으면 문서를 저장합니다—래스터화 없이 **레드액션된 문서 저장** 로직을 보여줍니다. + +### 일반적인 함정 및 문제 해결 +- **로그 출력 누락:** 각 `Log*` 메서드가 올바르게 오버라이드되었는지 확인합니다. +- **파일 접근 예외:** 애플리케이션이 원본 및 출력 경로에 대한 읽기/쓰기 권한을 가지고 있는지 확인합니다. +- **로거 연결 안 됨:** `RedactorSettings(logger)` 매개변수가 필수이며, 이를 생략하면 사용자 정의 로깅이 비활성화됩니다. + +## 실용적인 적용 사례 +1. **규정 준수 보고:** 로그 항목을 CSV 또는 데이터베이스로 내보내어 감사 추적을 만듭니다. +2. **오류 추적:** `LogError` 출력을 스캔하여 문제 파일을 빠르게 찾습니다. +3. **워크플로 자동화:** `LogWarning`이 호출될 때 하위 프로세스(예: 컴플라이언스 담당자 알림)를 트리거합니다. + +## 성능 고려 사항 +- **스트림을 즉시 해제**하여 메모리를 해제합니다. 특히 대량 배치를 처리할 때 중요합니다. +- **CPU 및 메모리 모니터링**을 대량 레드액션 중에 수행하고, 로거 동기화를 신중히 하여 병렬 처리 고려합니다. +- **업데이트 유지:** 최신 GroupDocs.Redaction 버전은 종종 성능 최적화 및 추가 로깅 훅을 포함합니다. + +## 결론 +**custom logger c#**를 구현하면 레드액션 파이프라인의 모든 단계에 대한 세밀한 통찰을 얻을 수 있어 규정 준수 기준을 충족하고 문제를 디버깅하기가 쉬워집니다. 여기서 제시한 접근 방식은 GroupDocs.Redaction for .NET과 원활히 작동하며, 이미 사용 중인 모든 .NET 로깅 프레임워크와 통합하도록 확장할 수 있습니다. + +--- + +## 자주 묻는 질문 + +**Q: GroupDocs.Redaction와 함께 custom logging을 사용하는 목적은 무엇인가요?** +A: custom logging은 규정 준수, 오류 추적 및 워크플로 최적화를 위해 레드액션을 추적하고 관리하는 데 도움이 됩니다. + +**Q: custom logger를 사용하여 오류를 어떻게 처리하나요?** +A: `CustomLogger` 클래스에서 `LogError`를 구현하고, `HasErrors` 플래그를 사용해 필요 시 처리를 중단할 수 있습니다. + +**Q: custom logging을 다른 시스템과 통합할 수 있나요?** +A: 예, 로거 메서드를 확장하여 로그 메시지를 CRM, ERP 또는 중앙 모니터링 도구로 전달할 수 있습니다. + +**Q: custom logging 구현 시 흔히 발생하는 함정은 무엇인가요?** +A: 메서드 구현 오류, `RedactorSettings(logger)` 누락, 파일 권한 문제 등이 가장 흔합니다. + +**Q: custom logging이 문서 레드액션 워크플로를 어떻게 개선하나요?** +A: 상세 로그는 실시간 가시성을 제공하고, 문제 해결을 간소화하며, 감사 요구사항을 충족합니다. + +## 리소스 + +- **문서:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API 레퍼런스:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **다운로드:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**마지막 업데이트:** 2026-03-28 +**테스트 환경:** GroupDocs.Redaction 23.11 for .NET +**작성자:** GroupDocs \ No newline at end of file diff --git a/content/polish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/polish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..581c5f31 --- /dev/null +++ b/content/polish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,183 @@ +--- +date: '2026-03-28' +description: Dowiedz się, jak zaimplementować własny logger C# w GroupDocs.Redaction + dla .NET, umożliwiając szczegółowe niestandardowe logowanie w .NET i ułatwiając + raportowanie zgodności. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Implementacja własnego loggera C# w GroupDocs.Redaction dla .NET +type: docs +url: /pl/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Implementacja własnego loggera c# w GroupDocs.Redaction dla .NET + +Efektywne zarządzanie redakcjami dokumentów jest kluczowe, szczególnie przy obsłudze wrażliwych informacji. W tym przewodniku dowiesz się **jak zaimplementować własny logger c#** z GroupDocs.Redaction dla .NET, co daje pełną kontrolę nad logowaniem, obsługą błędów i ścieżkami audytu. + +## Szybkie odpowiedzi +- **Co robi własny logger c#?** Rejestruje błędy, ostrzeżenia i komunikaty informacyjne podczas redakcji. +- **Która biblioteka udostępnia interfejs ILogger?** GroupDocs.Redaction dla .NET. +- **Czy mogę zapisać zredagowany dokument bez rasteryzacji?** Tak – użyj `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Czy potrzebna jest licencja do użytku produkcyjnego?** Wymagana jest pełna licencja do produkcji; dostępna jest wersja próbna do oceny. +- **Czy to podejście jest kompatybilne z .NET Core / .NET 6+?** Absolutnie – to samo API działa zarówno w .NET Framework, jak i .NET Core/5/6. + +## Czym jest własny logger c#? +**Własny logger c#** to klasa implementująca interfejs `ILogger` dostarczany przez GroupDocs.Redaction. Pozwala kierować komunikaty logów tam, gdzie potrzebujesz — konsola, plik, baza danych lub zewnętrzne systemy monitorujące — zapewniając przejrzysty podgląd procesu redakcji. + +## Dlaczego warto używać własnego logowania .net z GroupDocs.Redaction? +- **Zgodność i audyt:** Szczegółowe logi spełniają wymogi regulacyjne. +- **Widoczność błędów:** `LogError` i `LogWarning` zapewniają natychmiastową informację o problemach. +- **Elastyczność integracji:** Przekazuj logi do istniejących frameworków logowania .NET (Serilog, NLog, itp.). + +## Wymagania wstępne +- **GroupDocs.Redaction for .NET** zainstalowany (zobacz instalację poniżej). +- Środowisko programistyczne .NET (Visual Studio, VS Code lub CLI). +- Podstawowa znajomość C# oraz obsługi strumieni plików. + +## Instalacja + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Wyszukaj **"GroupDocs.Redaction"** i zainstaluj najnowszą wersję. + +## Uzyskanie licencji +- **Darmowa wersja próbna:** Przetestuj API z tymczasową licencją. +- **Licencja tymczasowa:** Uzyskaj pełny dostęp do funkcji na ograniczony czas. +- **Zakup:** Uzyskaj licencję wieczystą do wdrożeń produkcyjnych. + +## Przewodnik krok po kroku + +### Krok 1: Zdefiniuj własną klasę loggera (log warnings c#) + +Utwórz klasę implementującą `ILogger`. Klasa ta będzie przechwytywać błędy, ostrzeżenia i komunikaty informacyjne. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Wyjaśnienie:** Flaga `HasErrors` pomaga zdecydować, czy kontynuować przetwarzanie. Trzy metody odpowiadają trzem poziomom logowania, które będą potrzebne w większości scenariuszy redakcji. + +### Krok 2: Przygotuj ścieżki plików i otwórz dokument źródłowy + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Dlaczego to ważne:** Korzystanie z metod pomocniczych utrzymuje kod czystym i zapewnia, że folder wyjściowy istnieje przed próbą **zapisania zredagowanego dokumentu**. + +### Krok 3: Zastosuj redakcje używając własnego loggera + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Wyjaśnienie:** +1. `Redactor` jest tworzony z `RedactorSettings(logger)`, łącząc Twój `CustomLogger`. +2. Po zastosowaniu redakcji kod sprawdza `logger.HasErrors`. Jeśli nie wystąpiły błędy, dokument jest zapisywany — co demonstruje logikę **zapisania zredagowanego dokumentu** bez rasteryzacji. + +### Typowe pułapki i rozwiązywanie problemów +- **Brak wyjścia logu:** Zweryfikuj, że każda metoda `Log*` jest prawidłowo nadpisana. +- **Wyjątki dostępu do pliku:** Upewnij się, że aplikacja ma uprawnienia odczytu/zapisu zarówno do ścieżek źródłowych, jak i wyjściowych. +- **Logger nie podłączony:** Parametr `RedactorSettings(logger)` jest niezbędny; pominięcie go wyłącza własne logowanie. + +## Praktyczne zastosowania +1. **Raportowanie zgodności:** Eksportuj wpisy logów do CSV lub bazy danych w celu tworzenia ścieżek audytu. +2. **Śledzenie błędów:** Szybko zlokalizuj problematyczne pliki, przeszukując wyjście `LogError`. +3. **Automatyzacja przepływu pracy:** Uruchom procesy zależne (np. powiadomienie pracownika ds. zgodności) gdy wywołany zostanie `LogWarning`. + +## Uwagi dotyczące wydajności +- **Niezwłocznie zwalniaj strumienie** aby zwolnić pamięć, szczególnie przy przetwarzaniu dużych partii. +- **Monitoruj CPU i pamięć** podczas masowych redakcji; rozważ przetwarzanie dokumentów równolegle przy zachowaniu ostrożnej synchronizacji loggera. +- **Bądź na bieżąco:** Nowsze wersje GroupDocs.Redaction często zawierają optymalizacje wydajności i dodatkowe haki logowania. + +## Zakończenie + +Implementując **własny logger c#**, uzyskasz szczegółowy wgląd w każdy krok potoku redakcji, co ułatwia spełnianie standardów zgodności i debugowanie problemów. Podejście przedstawione tutaj działa płynnie z GroupDocs.Redaction dla .NET i może być rozszerzone o integrację z dowolnym frameworkiem logowania .NET, którego już używasz. + +--- + +## Najczęściej zadawane pytania + +**Q: Jaki jest cel własnego logowania z GroupDocs.Redaction?** +A: Własne logowanie pomaga śledzić i zarządzać redakcjami pod kątem zgodności, śledzenia błędów i optymalizacji przepływu pracy. + +**Q: Jak obsługiwać błędy przy użyciu własnego loggera?** +A: Zaimplementuj `LogError` w swojej klasie `CustomLogger`; flaga `HasErrors` pozwala w razie potrzeby zatrzymać przetwarzanie. + +**Q: Czy własne logowanie może być zintegrowane z innymi systemami?** +A: Tak, możesz przekazywać komunikaty logów do systemów CRM, ERP lub scentralizowanych narzędzi monitorujących, rozszerzając metody loggera. + +**Q: Jakie są typowe pułapki przy implementacji własnego logowania?** +A: Nieprawidłowe implementacje metod, brak `RedactorSettings(logger)` oraz problemy z uprawnieniami do plików są najczęstsze. + +**Q: Jak własne logowanie usprawnia przepływy pracy redakcji dokumentów?** +A: Szczegółowe logi zapewniają widoczność w czasie rzeczywistym, upraszczają rozwiązywanie problemów i spełniają wymogi audytu. + +## Zasoby + +- **Documentation:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API Reference:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Download:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Ostatnia aktualizacja:** 2026-03-28 +**Testowano z:** GroupDocs.Redaction 23.11 for .NET +**Autor:** GroupDocs \ No newline at end of file diff --git a/content/portuguese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/portuguese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..d4670d41 --- /dev/null +++ b/content/portuguese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,187 @@ +--- +date: '2026-03-28' +description: Aprenda a implementar um logger personalizado em C# no GroupDocs.Redaction + para .NET, permitindo registro detalhado personalizado no .NET e facilitando a geração + de relatórios de conformidade. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Implementar logger personalizado em C# no GroupDocs.Redaction para .NET +type: docs +url: /pt/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Implementar logger personalizado c# no GroupDocs.Redaction para .NET + +Gerenciar redações de documentos de forma eficiente é crítico, especialmente ao lidar com informações sensíveis. Neste guia você aprenderá **como implementar um logger personalizado c#** com GroupDocs.Redaction para .NET, dando controle total sobre registro, tratamento de erros e trilhas de auditoria. + +## Respostas rápidas +- **O que faz um logger personalizado c#?** Ele captura erros, avisos e mensagens informativas durante a redação. +- **Qual biblioteca fornece a interface ILogger?** GroupDocs.Redaction para .NET. +- **Posso salvar o documento redigido sem rasterização?** Sim – use `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Preciso de uma licença para uso em produção?** Uma licença completa é necessária para produção; uma avaliação está disponível para avaliação. +- **Esta abordagem é compatível com .NET Core / .NET 6+?** Absolutamente – a mesma API funciona em .NET Framework e .NET Core/5/6. + +## O que é um logger personalizado c#? +Um **custom logger c#** é uma classe que implementa a interface `ILogger` fornecida pelo GroupDocs.Redaction. Ela permite direcionar mensagens de log onde você precisar — console, arquivo, banco de dados ou sistemas de monitoramento externos — proporcionando uma visão clara do fluxo de trabalho de redação. + +## Por que usar logging personalizado .net com GroupDocs.Redaction? +- **Conformidade & Auditoria:** Logs detalhados atendem aos requisitos regulatórios. +- **Visibilidade de Erros:** `LogError` e `LogWarning` fornecem feedback imediato sobre problemas. +- **Flexibilidade de Integração:** Encaminhe logs para frameworks de logging .NET existentes (Serilog, NLog, etc.). + +## Pré-requisitos +- **GroupDocs.Redaction para .NET** instalado (veja a instalação abaixo). +- Um ambiente de desenvolvimento .NET (Visual Studio, VS Code ou CLI). +- Conhecimento básico de C# e familiaridade com streams de arquivos. + +## Instalação + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Pesquise por **"GroupDocs.Redaction"** e instale a versão mais recente. + +## Aquisição de Licença +- **Teste Gratuito:** Teste a API com uma licença temporária. +- **Licença Temporária:** Obtenha acesso total aos recursos por um período limitado. +- **Compra:** Obtenha uma licença perpétua para implantações de produção. + +## Guia passo a passo + +### Etapa 1: Definir uma classe de logger personalizada (log warnings c#) + +Crie uma classe que implemente `ILogger`. Esta classe capturará erros, avisos e mensagens informativas. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Explicação:** O sinalizador `HasErrors` ajuda a decidir se deve continuar o processamento. Os três métodos correspondem aos três níveis de log que você precisará na maioria dos cenários de redação. + +### Etapa 2: Preparar caminhos de arquivos e abrir o documento fonte + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Por que isso importa:** Usar métodos utilitários mantém seu código limpo e garante que a pasta de saída exista antes de tentar **salvar o documento redigido**. + +### Etapa 3: Aplicar redações usando o logger personalizado + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Explicação:** +1. O `Redactor` é instanciado com `RedactorSettings(logger)`, vinculando seu `CustomLogger`. +2. Após aplicar uma redação, o código verifica `logger.HasErrors`. Se não houver erros, o documento é salvo — demonstrando a lógica de **salvar documento redigido** sem rasterização. + +### Armadilhas comuns & Solução de problemas +- **Saída de log ausente:** Verifique se cada método `Log*` está corretamente sobrescrito. +- **Exceções de acesso a arquivos:** Garanta que a aplicação tenha permissões de leitura/escrita para os caminhos de origem e saída. +- **Logger não conectado:** O parâmetro `RedactorSettings(logger)` é essencial; omiti-lo desativa o logging personalizado. + +## Aplicações práticas + +1. **Relatórios de Conformidade:** Exporte entradas de log para CSV ou banco de dados para trilhas de auditoria. +2. **Rastreamento de Erros:** Localize rapidamente arquivos problemáticos escaneando a saída de `LogError`. +3. **Automação de Fluxo de Trabalho:** Dispare processos subsequentes (ex.: notificar um oficial de conformidade) quando `LogWarning` for invocado. + +## Considerações de desempenho + +- **Descartar streams prontamente** para liberar memória, especialmente ao processar grandes lotes. +- **Monitorar CPU & memória** durante redações em massa; considere processar documentos em paralelo com sincronização cuidadosa do logger. +- **Mantenha-se atualizado:** Versões mais recentes do GroupDocs.Redaction frequentemente incluem otimizações de desempenho e ganchos de logging adicionais. + +## Conclusão + +Ao implementar um **custom logger c#**, você obtém insight granular em cada etapa do pipeline de redação, facilitando o cumprimento de padrões de conformidade e a depuração de problemas. A abordagem mostrada aqui funciona perfeitamente com GroupDocs.Redaction para .NET e pode ser estendida para integrar-se a qualquer framework de logging .NET que você já use. + +--- + +## Perguntas Frequentes + +**Q: Qual é o objetivo do logging personalizado com GroupDocs.Redaction?** +A: O logging personalizado ajuda a rastrear e gerenciar redações para conformidade, rastreamento de erros e otimização de fluxo de trabalho. + +**Q: Como lidar com erros usando um logger personalizado?** +A: Implemente `LogError` na sua classe `CustomLogger`; o sinalizador `HasErrors` permite interromper o processamento se necessário. + +**Q: O logging personalizado pode ser integrado a outros sistemas?** +A: Sim, você pode encaminhar mensagens de log para CRM, ERP ou ferramentas de monitoramento centralizadas estendendo os métodos do logger. + +**Q: Quais são algumas armadilhas comuns ao implementar logging personalizado?** +A: Implementações incorretas de métodos, ausência de `RedactorSettings(logger)` e problemas de permissão de arquivos são as mais frequentes. + +**Q: Como o logging personalizado melhora os fluxos de trabalho de redação de documentos?** +A: Logs detalhados fornecem visibilidade em tempo real, simplificam a solução de problemas e atendem aos requisitos de auditoria. + +## Recursos + +- **Documentation:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API Reference:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Download:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Last Updated:** 2026-03-28 +**Tested With:** GroupDocs.Redaction 23.11 for .NET +**Author:** GroupDocs + +--- \ No newline at end of file diff --git a/content/russian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/russian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..1d71b85a --- /dev/null +++ b/content/russian/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,183 @@ +--- +date: '2026-03-28' +description: Узнайте, как реализовать пользовательский логгер C# в GroupDocs.Redaction + для .NET, обеспечивая детальное пользовательское логирование в .NET и упрощая составление + отчётов о соответствии. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Реализовать пользовательский логгер C# в GroupDocs.Redaction для .NET +type: docs +url: /ru/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Реализовать пользовательский логгер c# в GroupDocs.Redaction для .NET + +Эффективное управление редактированием документов имеет решающее значение, особенно при работе с конфиденциальной информацией. В этом руководстве вы узнаете **как реализовать пользовательский логгер c#** с GroupDocs.Redaction для .NET, получив полный контроль над журналированием, обработкой ошибок и аудиторскими следами. + +## Быстрые ответы +- **Что делает пользовательский логгер c#?** Он фиксирует ошибки, предупреждения и информационные сообщения во время редактирования. +- **Какая библиотека предоставляет интерфейс ILogger?** GroupDocs.Redaction для .NET. +- **Можно ли сохранить отредактированный документ без растеризации?** Да — используйте `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Нужна ли лицензия для использования в продакшене?** Для продакшена требуется полная лицензия; доступна пробная версия для оценки. +- **Совместим ли этот подход с .NET Core / .NET 6+?** Абсолютно — тот же API работает как в .NET Framework, так и в .NET Core/5/6. + +## Что такое пользовательский логгер c#? +Пользовательский логгер c# — это класс, реализующий интерфейс `ILogger`, предоставляемый GroupDocs.Redaction. Он позволяет направлять сообщения журнала туда, где вам нужно — в консоль, файл, базу данных или внешние системы мониторинга — обеспечивая ясный обзор процесса редактирования. + +## Зачем использовать пользовательское журналирование .net с GroupDocs.Redaction? +- **Соответствие и аудит:** Подробные журналы удовлетворяют нормативные требования. +- **Видимость ошибок:** `LogError` и `LogWarning` предоставляют мгновенную обратную связь о проблемах. +- **Гибкость интеграции:** Перенаправляйте журналы в существующие .NET фреймворки журналирования (Serilog, NLog и др.). + +## Требования +- **GroupDocs.Redaction для .NET** установлен (см. раздел установки ниже). +- Среда разработки .NET (Visual Studio, VS Code или CLI). +- Базовые знания C# и знакомство с файловыми потоками. + +## Установка + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Найдите **"GroupDocs.Redaction"** и установите последнюю версию. + +## Приобретение лицензии +- **Бесплатная пробная версия:** Протестировать API с временной лицензией. +- **Временная лицензия:** Получить полный доступ к функциям на ограниченный период. +- **Покупка:** Приобрести бессрочную лицензию для продакшн-развертываний. + +## Пошаговое руководство + +### Шаг 1: Определить пользовательский класс логгера (log warnings c#) + +Создайте класс, реализующий `ILogger`. Этот класс будет фиксировать ошибки, предупреждения и информационные сообщения. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Explanation:** Флаг `HasErrors` помогает решить, продолжать ли обработку. Три метода соответствуют трем уровням журналирования, которые потребуются в большинстве сценариев редактирования. + +### Шаг 2: Подготовить пути к файлам и открыть исходный документ + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Why this matters:** Использование вспомогательных методов делает код чистым и гарантирует, что папка вывода существует до попытки **сохранить отредактированный документ**. + +### Шаг 3: Применять редактирование, используя пользовательский логгер + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Explanation:** +1. `Redactor` создаётся с `RedactorSettings(logger)`, связывая ваш `CustomLogger`. +2. После применения редактирования код проверяет `logger.HasErrors`. Если ошибок нет, документ сохраняется — демонстрируя логику **save redacted document** без растеризации. + +### Распространённые ошибки и устранение неполадок +- **Отсутствует вывод журнала:** Убедитесь, что каждый метод `Log*` правильно переопределён. +- **Исключения доступа к файлам:** Убедитесь, что приложение имеет права чтения/записи для путей источника и вывода. +- **Логгер не подключён:** Параметр `RedactorSettings(logger)` обязателен; его отсутствие отключает пользовательское журналирование. + +## Практические применения +1. **Отчётность по соответствию:** Экспортировать записи журнала в CSV или базу данных для аудиторских следов. +2. **Отслеживание ошибок:** Быстро находить проблемные файлы, просматривая вывод `LogError`. +3. **Автоматизация рабочего процесса:** Запускать последующие процессы (например, уведомление сотрудника по соответствию) при вызове `LogWarning`. + +## Соображения по производительности +- **Своевременно освобождайте потоки** для освобождения памяти, особенно при обработке больших пакетов. +- **Отслеживайте CPU и память** во время массового редактирования; рассмотрите параллельную обработку документов с осторожной синхронизацией логгера. +- **Следите за обновлениями:** Новые версии GroupDocs.Redaction часто включают оптимизации производительности и дополнительные точки журналирования. + +## Заключение + +Реализовав **пользовательский логгер c#**, вы получаете детальный контроль над каждым шагом конвейера редактирования, упрощая соблюдение стандартов соответствия и отладку проблем. Представленный подход без проблем работает с GroupDocs.Redaction для .NET и может быть расширен для интеграции с любым .NET фреймворком журналирования, который вы уже используете. + +--- + +## Часто задаваемые вопросы + +**Q: Какова цель пользовательского журналирования с GroupDocs.Redaction?** +A: Пользовательское журналирование помогает отслеживать и управлять редактированием для соответствия, отслеживания ошибок и оптимизации рабочего процесса. + +**Q: Как обрабатывать ошибки с помощью пользовательского логгера?** +A: Реализуйте `LogError` в вашем классе `CustomLogger`; флаг `HasErrors` позволяет при необходимости остановить обработку. + +**Q: Можно ли интегрировать пользовательское журналирование с другими системами?** +A: Да, вы можете перенаправлять сообщения журнала в CRM, ERP или централизованные инструменты мониторинга, расширив методы логгера. + +**Q: Какие распространённые ошибки при реализации пользовательского журналирования?** +A: Неправильные реализации методов, отсутствие `RedactorSettings(logger)` и проблемы с правами доступа к файлам — самые частые. + +**Q: Как пользовательское журналирование улучшает рабочие процессы редактирования документов?** +A: Подробные журналы обеспечивают видимость в реальном времени, упрощают устранение неполадок и удовлетворяют требования аудита. + +## Ресурсы + +- **Документация:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **Ссылка на API:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Скачать:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Последнее обновление:** 2026-03-28 +**Тестировано с:** GroupDocs.Redaction 23.11 for .NET +**Автор:** GroupDocs \ No newline at end of file diff --git a/content/spanish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/spanish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..7c6c2cec --- /dev/null +++ b/content/spanish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,183 @@ +--- +date: '2026-03-28' +description: Aprenda cómo implementar un registrador personalizado en C# en GroupDocs.Redaction + para .NET, habilitando un registro detallado personalizado en .NET y facilitando + la generación de informes de cumplimiento. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Implementar un logger personalizado en C# en GroupDocs.Redaction para .NET +type: docs +url: /es/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Implementar un logger personalizado c# en GroupDocs.Redaction para .NET + +Gestionar las redacciones de documentos de manera eficiente es fundamental, especialmente al manejar información sensible. En esta guía aprenderás **cómo implementar un logger personalizado c#** con GroupDocs.Redaction para .NET, dándote control total sobre el registro, el manejo de errores y los registros de auditoría. + +## Respuestas rápidas +- **¿Qué hace un logger personalizado c#?** Captura errores, advertencias y mensajes informativos durante la redacción. +- **¿Qué biblioteca proporciona la interfaz ILogger?** GroupDocs.Redaction para .NET. +- **¿Puedo guardar el documento redactado sin rasterización?** Sí – usa `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **¿Necesito una licencia para uso en producción?** Se requiere una licencia completa para producción; hay una versión de prueba disponible para evaluación. +- **¿Este enfoque es compatible con .NET Core / .NET 6+?** Absolutamente – la misma API funciona tanto en .NET Framework como en .NET Core/5/6. + +## Qué es un logger personalizado c#? +Un **logger personalizado c#** es una clase que implementa la interfaz `ILogger` proporcionada por GroupDocs.Redaction. Te permite dirigir los mensajes de registro a donde necesites—consola, archivo, base de datos o sistemas de monitoreo externos—mientras te brinda una visión clara del flujo de trabajo de la redacción. + +## ¿Por qué usar registro personalizado .net con GroupDocs.Redaction? +- **Cumplimiento y auditoría:** Los registros detallados cumplen con los requisitos regulatorios. +- **Visibilidad de errores:** `LogError` y `LogWarning` te brindan retroalimentación inmediata sobre los problemas. +- **Flexibilidad de integración:** Reenvía los registros a los frameworks de registro .NET existentes (Serilog, NLog, etc.). + +## Requisitos previos +- **GroupDocs.Redaction para .NET** instalado (ver instalación más abajo). +- Un entorno de desarrollo .NET (Visual Studio, VS Code o CLI). +- Conocimientos básicos de C# y familiaridad con flujos de archivos. + +## Instalación + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Busca **"GroupDocs.Redaction"** e instala la última versión. + +## Obtención de licencia +- **Prueba gratuita:** Prueba la API con una licencia temporal. +- **Licencia temporal:** Obtén acceso completo a las funciones por un período limitado. +- **Compra:** Obtén una licencia perpetua para despliegues en producción. + +## Guía paso a paso + +### Paso 1: Definir una clase de logger personalizada (registro de advertencias c#) + +Crea una clase que implemente `ILogger`. Esta clase capturará errores, advertencias y mensajes informativos. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Explicación:** La bandera `HasErrors` te ayuda a decidir si continuar procesando. Los tres métodos corresponden a los tres niveles de registro que necesitarás en la mayoría de los escenarios de redacción. + +### Paso 2: Preparar rutas de archivo y abrir el documento fuente + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Por qué es importante:** Usar métodos utilitarios mantiene tu código limpio y asegura que la carpeta de salida exista antes de intentar **guardar el documento redactado**. + +### Paso 3: Aplicar redacciones usando el logger personalizado + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Explicación:** +1. El `Redactor` se instancia con `RedactorSettings(logger)`, vinculando tu `CustomLogger`. +2. Después de aplicar una redacción, el código verifica `logger.HasErrors`. Si no se produjeron errores, el documento se guarda—demostrando la lógica de **guardar documento redactado** sin rasterización. + +## Errores comunes y solución de problemas +- **Salida de registro ausente:** Verifica que cada método `Log*` esté correctamente sobrescrito. +- **Excepciones de acceso a archivos:** Asegúrate de que la aplicación tenga permisos de lectura/escritura para las rutas de origen y salida. +- **Logger no conectado:** El parámetro `RedactorSettings(logger)` es esencial; omitirlo desactiva el registro personalizado. + +## Aplicaciones prácticas +1. **Informe de cumplimiento:** Exporta entradas de registro a un CSV o base de datos para rastros de auditoría. +2. **Seguimiento de errores:** Localiza rápidamente archivos problemáticos escaneando la salida de `LogError`. +3. **Automatización de flujo de trabajo:** Activa procesos posteriores (p. ej., notificar a un oficial de cumplimiento) cuando se invoque `LogWarning`. + +## Consideraciones de rendimiento +- **Descarta los streams rápidamente** para liberar memoria, especialmente al procesar lotes grandes. +- **Monitorea CPU y memoria** durante redacciones masivas; considera procesar documentos en paralelo con una sincronización cuidadosa del logger. +- **Mantente actualizado:** Las versiones más recientes de GroupDocs.Redaction a menudo incluyen optimizaciones de rendimiento y ganchos de registro adicionales. + +## Conclusión + +Al implementar un **logger personalizado c#**, obtienes una visión granular de cada paso del pipeline de redacción, facilitando el cumplimiento de los estándares de cumplimiento y la depuración de problemas. El enfoque mostrado aquí funciona sin problemas con GroupDocs.Redaction para .NET y puede ampliarse para integrarse con cualquier framework de registro .NET que ya utilices. + +--- + +## Preguntas frecuentes + +**Q: ¿Cuál es el propósito del registro personalizado con GroupDocs.Redaction?** +A: El registro personalizado ayuda a rastrear y gestionar las redacciones para cumplimiento, seguimiento de errores y optimización del flujo de trabajo. + +**Q: ¿Cómo manejo los errores usando un logger personalizado?** +A: Implementa `LogError` en tu clase `CustomLogger`; la bandera `HasErrors` te permite detener el procesamiento si es necesario. + +**Q: ¿Puede integrarse el registro personalizado con otros sistemas?** +A: Sí, puedes reenviar los mensajes de registro a CRM, ERP o herramientas de monitoreo centralizadas extendiendo los métodos del logger. + +**Q: ¿Cuáles son algunos errores comunes al implementar registro personalizado?** +A: Implementaciones incorrectas de métodos, ausencia de `RedactorSettings(logger)` y problemas de permisos de archivos son los más frecuentes. + +**Q: ¿Cómo mejora el registro personalizado los flujos de trabajo de redacción de documentos?** +A: Los registros detallados proporcionan visibilidad en tiempo real, simplifican la solución de problemas y cumplen con los requisitos de auditoría. + +## Recursos + +- **Documentación:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **Referencia API:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Descarga:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Última actualización:** 2026-03-28 +**Probado con:** GroupDocs.Redaction 23.11 para .NET +**Autor:** GroupDocs \ No newline at end of file diff --git a/content/swedish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/swedish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..50bf1f60 --- /dev/null +++ b/content/swedish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,182 @@ +--- +date: '2026-03-28' +description: Lär dig hur du implementerar en anpassad logger i C# i GroupDocs.Redaction + för .NET, vilket möjliggör detaljerad anpassad loggning i .NET och enklare efterlevnadsrapportering. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Implementera en anpassad loggare i C# i GroupDocs.Redaction för .NET +type: docs +url: /sv/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Implementera anpassad logger c# i GroupDocs.Redaction för .NET + +Att hantera dokumentredigeringar effektivt är kritiskt, särskilt när man hanterar känslig information. I den här guiden lär du dig **hur du implementerar en anpassad logger c#** med GroupDocs.Redaction för .NET, vilket ger dig full kontroll över loggning, felhantering och revisionsspår. + +## Snabba svar +- **Vad gör en anpassad logger c#?** Den fångar fel, varningar och informationsmeddelanden under redigering. +- **Vilket bibliotek tillhandahåller ILogger‑gränssnittet?** GroupDocs.Redaction för .NET. +- **Kan jag spara det redigerade dokumentet utan rasterisering?** Ja – använd `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Behöver jag en licens för produktionsanvändning?** En full licens krävs för produktion; en provlicens finns tillgänglig för utvärdering. +- **Är detta tillvägagångssätt kompatibelt med .NET Core / .NET 6+?** Absolut – samma API fungerar både i .NET Framework och .NET Core/5/6. + +## Vad är en anpassad logger c#? +En **custom logger c#** är en klass som implementerar `ILogger`‑gränssnittet som levereras av GroupDocs.Redaction. Den låter dig dirigera loggmeddelanden dit du behöver – konsol, fil, databas eller externa övervakningssystem – samtidigt som den ger dig en tydlig bild av redigeringsarbetsflödet. + +## Varför använda anpassad loggning .net med GroupDocs.Redaction? +- **Efterlevnad & Revision:** Detaljerade loggar uppfyller regulatoriska krav. +- **Felinsyn:** `LogError` och `LogWarning` ger dig omedelbar återkoppling på problem. +- **Integrationsflexibilitet:** Skicka vidare loggar till befintliga .NET‑loggningsramverk (Serilog, NLog, etc.). + +## Förutsättningar +- **GroupDocs.Redaction för .NET** installerat (se installationen nedan). +- En .NET‑utvecklingsmiljö (Visual Studio, VS Code eller CLI). +- Grundläggande C#‑kunskaper och bekantskap med filströmmar. + +## Installation + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Sök efter **"GroupDocs.Redaction"** och installera den senaste versionen. + +## Licensanskaffning +- **Gratis prov:** Testa API:et med en tillfällig licens. +- **Tillfällig licens:** Få full åtkomst till funktioner under en begränsad period. +- **Köp:** Skaffa en evig licens för produktionsdistributioner. + +## Steg‑för‑steg‑guide + +### Steg 1: Definiera en anpassad logger-klass (logga varningar c#) + +Skapa en klass som implementerar `ILogger`. Denna klass kommer att fånga fel, varningar och informationsmeddelanden. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Förklaring:** `HasErrors`‑flaggan hjälper dig att avgöra om du ska fortsätta bearbetningen. De tre metoderna motsvarar de tre loggnivåer du kommer att behöva i de flesta redigeringsscenarier. + +### Steg 2: Förbered filsökvägar och öppna källdokumentet + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Varför detta är viktigt:** Att använda hjälpfunktioner håller din kod ren och säkerställer att målmappen finns innan du försöker **spara redigerat dokument**. + +### Steg 3: Tillämpa redigeringar medan du använder den anpassade loggern + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Förklaring:** +1. `Redactor` skapas med `RedactorSettings(logger)`, vilket länkar din `CustomLogger`. +2. Efter att en redigering har tillämpats kontrollerar koden `logger.HasErrors`. Om inga fel uppstod sparas dokumentet – vilket demonstrerar logiken för **spara redigerat dokument** utan rasterisering. + +### Vanliga fallgropar & felsökning +- **Saknad loggutdata:** Verifiera att varje `Log*`‑metod är korrekt överskriven. +- **Filåtkomst‑undantag:** Säkerställ att applikationen har läs-/skrivrättigheter för både källa och målvägar. +- **Logger ej ansluten:** Parametern `RedactorSettings(logger)` är avgörande; om den utelämnas inaktiveras anpassad loggning. + +## Praktiska tillämpningar +1. **Efterlevnadsrapportering:** Exportera loggposter till en CSV eller databas för revisionsspår. +2. **Felföljning:** Lokalisera snabbt problematiska filer genom att skanna `LogError`‑utdata. +3. **Arbetsflödesautomation:** Aktivera efterföljande processer (t.ex. meddela en efterlevnadsansvarig) när `LogWarning` anropas. + +## Prestandaöverväganden +- **Avsluta strömmar omedelbart** för att frigöra minne, särskilt vid bearbetning av stora satser. +- **Övervaka CPU & minne** under massredigeringar; överväg att bearbeta dokument parallellt med noggrann logger‑synkronisering. +- **Håll dig uppdaterad:** Nyare versioner av GroupDocs.Redaction innehåller ofta prestandaoptimeringar och ytterligare logg‑krokar. + +## Slutsats + +Genom att implementera en **custom logger c#** får du detaljerad insikt i varje steg av redigeringspipeline, vilket gör det enklare att uppfylla efterlevnadsstandarder och felsöka problem. Tillvägagångssättet som visas här fungerar sömlöst med GroupDocs.Redaction för .NET och kan utökas för att integreras med vilket .NET‑loggningsramverk du redan använder. + +--- + +## Vanliga frågor + +**Q: Vad är syftet med anpassad loggning med GroupDocs.Redaction?** +A: Anpassad loggning hjälper till att spåra och hantera redigeringar för efterlevnad, felspårning och arbetsflödesoptimering. + +**Q: Hur hanterar jag fel med en anpassad logger?** +A: Implementera `LogError` i din `CustomLogger`‑klass; `HasErrors`‑flaggan låter dig stoppa bearbetningen om det behövs. + +**Q: Kan anpassad loggning integreras med andra system?** +A: Ja, du kan vidarebefordra loggmeddelanden till CRM, ERP eller centrala övervakningsverktyg genom att utöka logger‑metoderna. + +**Q: Vilka är vanliga fallgropar vid implementering av anpassad loggning?** +A: Felaktiga metodimplementationer, saknad `RedactorSettings(logger)`, och filbehörighetsproblem är de vanligaste. + +**Q: Hur förbättrar anpassad loggning arbetsflöden för dokumentredigering?** +A: Detaljerade loggar ger realtidsinsyn, förenklar felsökning och uppfyller revisionskrav. + +## Resurser + +- **Dokumentation:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API‑referens:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Nedladdning:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Senast uppdaterad:** 2026-03-28 +**Testad med:** GroupDocs.Redaction 23.11 for .NET +**Författare:** GroupDocs \ No newline at end of file diff --git a/content/thai/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/thai/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..243617a3 --- /dev/null +++ b/content/thai/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,182 @@ +--- +date: '2026-03-28' +description: เรียนรู้วิธีการสร้าง Logger แบบกำหนดเองใน C# สำหรับ GroupDocs.Redaction + บน .NET เพื่อให้สามารถบันทึกข้อมูลอย่างละเอียดและอำนวยความสะดวกในการรายงานการปฏิบัติตามข้อกำหนด. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: นำ Logger แบบกำหนดเองใน C# ไปใช้กับ GroupDocs.Redaction สำหรับ .NET +type: docs +url: /th/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# ใช้งาน custom logger c# ใน GroupDocs.Redaction สำหรับ .NET + +การจัดการการลบข้อมูลในเอกสารอย่างมีประสิทธิภาพเป็นสิ่งสำคัญ โดยเฉพาะเมื่อจัดการข้อมูลที่ละเอียดอ่อน ในคู่มือนี้คุณจะได้เรียนรู้ **วิธีการใช้งาน custom logger c#** กับ GroupDocs.Redaction สำหรับ .NET ซึ่งจะให้คุณควบคุมการบันทึก, การจัดการข้อผิดพลาด, และบันทึกการตรวจสอบได้อย่างเต็มที่. + +## คำตอบสั้น +- **custom logger c# ทำอะไร?** มันบันทึกข้อผิดพลาด, คำเตือน, และข้อความข้อมูลระหว่างการลบข้อมูล. +- **ไลบรารีใดให้ส่วนต่อประสาน ILogger?** GroupDocs.Redaction สำหรับ .NET. +- **ฉันสามารถบันทึกเอกสารที่ลบข้อมูลแล้วโดยไม่ทำ rasterization ได้หรือไม่?** ใช่ – ใช้ `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **ฉันต้องการใบอนุญาตสำหรับการใช้งานในผลิตภัณฑ์หรือไม่?** จำเป็นต้องมีใบอนุญาตเต็มสำหรับการผลิต; มีรุ่นทดลองสำหรับการประเมินผล. +- **วิธีนี้เข้ากันได้กับ .NET Core / .NET 6+ หรือไม่?** แน่นอน – API เดียวกันทำงานได้ทั้งบน .NET Framework และ .NET Core/5/6. + +## custom logger c# คืออะไร? +**custom logger c#** คือคลาสที่ทำการ implement ส่วนต่อประสาน `ILogger` ที่จัดหาโดย GroupDocs.Redaction ซึ่งทำให้คุณสามารถส่งข้อความบันทึกไปยังที่ที่ต้องการ—คอนโซล, ไฟล์, ฐานข้อมูล, หรือระบบตรวจสอบภายนอก—พร้อมให้มุมมองที่ชัดเจนของกระบวนการลบข้อมูล. + +## ทำไมต้องใช้ custom logging .net กับ GroupDocs.Redaction? +- **Compliance & Auditing:** บันทึกรายละเอียดช่วยตอบสนองข้อกำหนดตามกฎระเบียบ. +- **Error Visibility:** `LogError` และ `LogWarning` ให้ข้อเสนอแนะทันทีเกี่ยวกับปัญหา. +- **Integration Flexibility:** ส่งต่อบันทึกไปยังเฟรมเวิร์กการบันทึกของ .NET ที่มีอยู่ (Serilog, NLog, ฯลฯ). + +## ข้อกำหนดเบื้องต้น +- **GroupDocs.Redaction for .NET** ติดตั้งแล้ว (ดูการติดตั้งด้านล่าง). +- สภาพแวดล้อมการพัฒนา .NET (Visual Studio, VS Code, หรือ CLI). +- ความรู้พื้นฐานของ C# และความคุ้นเคยกับไฟล์สตรีม. + +## การติดตั้ง + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +ค้นหา **"GroupDocs.Redaction"** และติดตั้งเวอร์ชันล่าสุด. + +## การรับใบอนุญาต +- **Free Trial:** ทดสอบ API ด้วยใบอนุญาตชั่วคราว. +- **Temporary License:** รับการเข้าถึงฟีเจอร์ทั้งหมดในช่วงเวลาจำกัด. +- **Purchase:** ซื้อใบอนุญาตถาวรสำหรับการใช้งานในผลิตภัณฑ์. + +## คู่มือขั้นตอนต่อขั้นตอน + +### ขั้นตอนที่ 1: กำหนดคลาส custom logger (log warnings c#) + +สร้างคลาสที่ทำการ implement `ILogger`. คลาสนี้จะบันทึกข้อผิดพลาด, คำเตือน, และข้อความข้อมูล. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Explanation:** ธง `HasErrors` ช่วยให้คุณตัดสินใจว่าจะดำเนินการต่อหรือไม่ วิธีการทั้งสามสอดคล้องกับระดับการบันทึกสามระดับที่คุณจะต้องใช้ในสถานการณ์การลบข้อมูลส่วนใหญ่. + +### ขั้นตอนที่ 2: เตรียมเส้นทางไฟล์และเปิดเอกสารต้นฉบับ + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Why this matters:** การใช้เมธอดยูทิลิตี้ทำให้โค้ดของคุณสะอาดและรับประกันว่าโฟลเดอร์ผลลัพธ์มีอยู่ก่อนที่คุณจะพยายาม **บันทึกเอกสารที่ลบข้อมูลแล้ว**. + +### ขั้นตอนที่ 3: ใช้การลบข้อมูลพร้อมกับ custom logger + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Explanation:** +1. `Redactor` ถูกสร้างด้วย `RedactorSettings(logger)`, เชื่อมต่อกับ `CustomLogger` ของคุณ. +2. หลังจากทำการลบข้อมูล, โค้ดจะตรวจสอบ `logger.HasErrors`. หากไม่มีข้อผิดพลาดเกิดขึ้น, เอกสารจะถูกบันทึก—แสดงให้เห็นตรรกะ **บันทึกเอกสารที่ลบข้อมูลแล้ว** โดยไม่ต้อง rasterization. + +### ข้อผิดพลาดทั่วไป & การแก้ไขปัญหา +- **Missing log output:** ตรวจสอบว่าแต่ละเมธอด `Log*` ถูก override อย่างถูกต้อง. +- **File access exceptions:** ตรวจสอบว่าแอปพลิเคชันมีสิทธิ์อ่าน/เขียนสำหรับเส้นทางต้นฉบับและผลลัพธ์. +- **Logger not wired:** พารามิเตอร์ `RedactorSettings(logger)` มีความสำคัญ; การละเว้นจะทำให้การบันทึกแบบ custom ไม่ทำงาน. + +## การประยุกต์ใช้งานจริง +1. **Compliance Reporting:** ส่งออกรายการบันทึกเป็น CSV หรือฐานข้อมูลเพื่อเป็นบันทึกการตรวจสอบ. +2. **Error Tracking:** ค้นหาไฟล์ที่มีปัญหาอย่างรวดเร็วโดยสแกนผลลัพธ์ของ `LogError`. +3. **Workflow Automation:** เรียกกระบวนการต่อเนื่อง (เช่น การแจ้งผู้รับผิดชอบด้าน compliance) เมื่อ `LogWarning` ถูกเรียกใช้. + +## พิจารณาด้านประสิทธิภาพ +- **Dispose streams promptly** เพื่อปล่อยหน่วยความจำ, โดยเฉพาะเมื่อประมวลผลชุดข้อมูลขนาดใหญ่. +- **Monitor CPU & memory** ระหว่างการลบข้อมูลเป็นจำนวนมาก; พิจารณาประมวลผลเอกสารแบบขนานพร้อมการซิงโครไนซ์ logger อย่างระมัดระวัง. +- **Stay updated:** เวอร์ชันใหม่ของ GroupDocs.Redaction มักมีการปรับปรุงประสิทธิภาพและ hook การบันทึกเพิ่มเติม. + +## สรุป + +โดยการ implement **custom logger c#**, คุณจะได้ข้อมูลเชิงลึกระดับละเอียดในทุกขั้นตอนของกระบวนการลบข้อมูล, ทำให้ง่ายต่อการปฏิบัติตามมาตรฐาน compliance และการดีบักปัญหา วิธีการที่แสดงนี้ทำงานอย่างไร้รอยต่อกับ GroupDocs.Redaction สำหรับ .NET และสามารถขยายเพื่อรวมกับเฟรมเวิร์กการบันทึกของ .NET ใด ๆ ที่คุณใช้อยู่แล้ว. + +--- + +## คำถามที่พบบ่อย + +**Q: จุดประสงค์ของ custom logging กับ GroupDocs.Redaction คืออะไร?** +A: Custom logging ช่วยติดตามและจัดการการลบข้อมูลเพื่อการปฏิบัติตาม, การติดตามข้อผิดพลาด, และการปรับปรุง workflow. + +**Q: ฉันจะจัดการข้อผิดพลาดด้วย custom logger อย่างไร?** +A: Implement `LogError` ในคลาส `CustomLogger` ของคุณ; ธง `HasErrors` ทำให้คุณสามารถหยุดการประมวลผลได้หากจำเป็น. + +**Q: สามารถรวม custom logging กับระบบอื่นได้หรือไม่?** +A: ได้, คุณสามารถส่งต่อข้อความบันทึกไปยัง CRM, ERP, หรือเครื่องมือมอนิเตอร์ศูนย์กลางโดยการขยายเมธอดของ logger. + +**Q: ข้อผิดพลาดทั่วไปเมื่อทำ custom logging มีอะไรบ้าง?** +A: การ implement เมธอดไม่ถูกต้อง, การลืม `RedactorSettings(logger)`, และปัญหาการอนุญาตไฟล์เป็นปัญหาที่พบบ่อยที่สุด. + +**Q: custom logging ช่วยปรับปรุง workflow การลบข้อมูลในเอกสารอย่างไร?** +A: บันทึกรายละเอียดให้มองเห็นแบบเรียลไทม์, ทำให้การแก้ปัญหาง่ายขึ้น, และตอบสนองความต้องการการตรวจสอบ. + +## แหล่งข้อมูล + +- **Documentation:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API Reference:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Download:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**อัปเดตล่าสุด:** 2026-03-28 +**ทดสอบกับ:** GroupDocs.Redaction 23.11 for .NET +**ผู้เขียน:** GroupDocs \ No newline at end of file diff --git a/content/turkish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/turkish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..2af8ba96 --- /dev/null +++ b/content/turkish/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,182 @@ +--- +date: '2026-03-28' +description: GroupDocs.Redaction for .NET'te C# kullanarak özel bir logger nasıl uygulanır, + ayrıntılı özel günlük kaydı ve daha kolay uyumluluk raporlaması sağlar. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: GroupDocs.Redaction for .NET'te C# ile özel logger uygulama +type: docs +url: /tr/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# GroupDocs.Redaction için .NET'te özel logger c# uygulama + +Belge redaksiyonlarını verimli bir şekilde yönetmek kritik öneme sahiptir, özellikle hassas bilgilerle çalışırken. Bu rehberde GroupDocs.Redaction for .NET ile **özel bir logger c# nasıl uygulanır** öğrenecek ve kayıt, hata yönetimi ve denetim izleri üzerinde tam kontrol elde edeceksiniz. + +## Hızlı Yanıtlar +- **Özel bir logger c# ne yapar?** Redaksiyon sırasında hata, uyarı ve bilgilendirme mesajlarını yakalar. +- **ILogger arayüzünü hangi kütüphane sağlar?** GroupDocs.Redaction for .NET. +- **Redakte edilmiş belgeyi rasterizasyon olmadan kaydedebilir miyim?** Evet – `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })` kullanın. +- **Üretim kullanımında lisansa ihtiyacım var mı?** Üretim için tam lisans gereklidir; değerlendirme için bir deneme sürümü mevcuttur. +- **Bu yaklaşım .NET Core / .NET 6+ ile uyumlu mu?** Kesinlikle – aynı API .NET Framework ve .NET Core/5/6 arasında çalışır. + +## Özel bir logger c# nedir? +Bir **custom logger c#**, GroupDocs.Redaction tarafından sağlanan `ILogger` arayüzünü uygulayan bir sınıftır. Günlük mesajlarını istediğiniz yere—konsola, dosyaya, veritabanına veya harici izleme sistemlerine—yönlendirmenizi sağlar ve redaksiyon iş akışının net bir görünümünü sunar. + +## GroupDocs.Redaction ile .net'te özel günlükleme neden kullanılmalı? +- **Uyumluluk & Denetim:** Ayrıntılı günlükler düzenleyici gereksinimleri karşılar. +- **Hata Görünürlüğü:** `LogError` ve `LogWarning` sorunlar hakkında anlık geri bildirim sağlar. +- **Entegrasyon Esnekliği:** Günlükleri mevcut .NET günlükleme çerçevelerine (Serilog, NLog vb.) yönlendirin. + +## Önkoşullar +- **GroupDocs.Redaction for .NET** yüklü (aşağıdaki kurulum bölümüne bakın). +- .NET geliştirme ortamı (Visual Studio, VS Code veya CLI). +- Temel C# bilgisi ve dosya akışlarına aşinalık. + +## Kurulum + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +**"GroupDocs.Redaction"** aratın ve en son sürümü kurun. + +## Lisans Edinimi +- **Ücretsiz Deneme:** API'yi geçici bir lisansla test edin. +- **Geçici Lisans:** Sınırlı bir süre tam özellik erişimi elde edin. +- **Satın Alma:** Üretim dağıtımları için kalıcı bir lisans edinin. + +## Adım‑Adım Kılavuz + +### Adım 1: Özel bir logger sınıfı tanımlayın (log warnings c#) + +`ILogger` arayüzünü uygulayan bir sınıf oluşturun. Bu sınıf hata, uyarı ve bilgilendirme mesajlarını yakalayacaktır. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Açıklama:** `HasErrors` bayrağı, işleme devam edip etmeyeceğinize karar vermenize yardımcı olur. Üç yöntem, çoğu redaksiyon senaryosunda ihtiyaç duyacağınız üç günlük seviyesine karşılık gelir. + +### Adım 2: Dosya yollarını hazırlayın ve kaynak belgeyi açın + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Neden Önemli:** Yardımcı yöntemleri kullanmak kodunuzu temiz tutar ve **redakte edilmiş belgeyi kaydet**meden önce çıktı klasörünün var olduğundan emin olmanızı sağlar. + +### Adım 3: Özel logger'ı kullanarak redaksiyonları uygulayın + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Açıklama:** +1. `Redactor`, `RedactorSettings(logger)` ile örneklenir ve `CustomLogger`'ınızı bağlar. +2. Bir redaksiyon uygulandıktan sonra kod `logger.HasErrors` kontrol eder. Hata oluşmadıysa belge kaydedilir—rasterizasyon olmadan **redakte edilmiş belgeyi kaydet** mantığını gösterir. + +### Yaygın Tuzaklar & Sorun Giderme +- **Eksik günlük çıktısı:** Her `Log*` metodunun doğru şekilde geçersiz kılındığını doğrulayın. +- **Dosya erişim istisnaları:** Uygulamanın kaynak ve çıktı yolları için okuma/yazma izinlerine sahip olduğundan emin olun. +- **Logger bağlanmamış:** `RedactorSettings(logger)` parametresi gereklidir; atlanması özel günlüklemeyi devre dışı bırakır. + +## Pratik Uygulamalar +1. **Uyumluluk Raporlaması:** Günlük girişlerini denetim izleri için CSV veya veritabanına dışa aktarın. +2. **Hata İzleme:** `LogError` çıktısını tarayarak sorunlu dosyaları hızlıca bulun. +3. **İş Akışı Otomasyonu:** `LogWarning` tetiklendiğinde aşağı akış süreçlerini (ör. uyumluluk sorumlusunu bilgilendirme) başlatın. + +## Performans Düşünceleri +- **Akışları hızlıca dispose edin** bellek serbest bırakmak için, özellikle büyük toplu işlemlerde. +- **CPU ve belleği izleyin** toplu redaksiyon sırasında; logger senkronizasyonuna dikkat ederek belgeleri paralel işleme almayı düşünün. +- **Güncel kalın:** GroupDocs.Redaction'ın yeni sürümleri genellikle performans iyileştirmeleri ve ek günlükleme kancaları içerir. + +## Sonuç + +Bir **custom logger c#** uygulayarak redaksiyon hattının her adımına ayrıntılı bir içgörü elde eder, uyumluluk standartlarını karşılamayı ve sorunları ayıklamayı kolaylaştırırsınız. Burada gösterilen yaklaşım GroupDocs.Redaction for .NET ile sorunsuz çalışır ve zaten kullandığınız herhangi bir .NET günlükleme çerçevesiyle entegrasyon için genişletilebilir. + +--- + +## Sıkça Sorulan Sorular + +**Q: GroupDocs.Redaction ile özel günlüklemenin amacı nedir?** +A: Özel günlükleme, uyumluluk, hata takibi ve iş akışı optimizasyonu için redaksiyonları izlemeye ve yönetmeye yardımcı olur. + +**Q: Özel bir logger kullanarak hataları nasıl yönetirim?** +A: `CustomLogger` sınıfınızda `LogError` metodunu uygulayın; `HasErrors` bayrağı gerektiğinde işleme durdurmanıza olanak tanır. + +**Q: Özel günlükleme diğer sistemlerle entegre edilebilir mi?** +A: Evet, logger metodlarını genişleterek günlük mesajlarını CRM, ERP veya merkezi izleme araçlarına yönlendirebilirsiniz. + +**Q: Özel günlükleme uygularken sık karşılaşılan tuzaklar nelerdir?** +A: Yanlış metod uygulamaları, eksik `RedactorSettings(logger)`, ve dosya izin sorunları en yaygın olanlardır. + +**Q: Özel günlükleme belge redaksiyon iş akışlarını nasıl iyileştirir?** +A: Ayrıntılı günlükler gerçek zamanlı görünürlük sağlar, sorun giderme sürecini basitleştirir ve denetim gereksinimlerini karşılar. + +## Kaynaklar + +- **Dokümantasyon:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **API Referansı:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **İndirme:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Son Güncelleme:** 2026-03-28 +**Test Edilen:** GroupDocs.Redaction 23.11 for .NET +**Yazar:** GroupDocs \ No newline at end of file diff --git a/content/vietnamese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md b/content/vietnamese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md new file mode 100644 index 00000000..15702590 --- /dev/null +++ b/content/vietnamese/net/advanced-redaction/custom-logging-groupdocs-redaction-net/_index.md @@ -0,0 +1,182 @@ +--- +date: '2026-03-28' +description: Tìm hiểu cách triển khai một logger tùy chỉnh bằng C# trong GroupDocs.Redaction + cho .NET, cho phép ghi log chi tiết tùy chỉnh và báo cáo tuân thủ dễ dàng hơn. +keywords: +- custom logger c# +- custom logging .net +- save redacted document +- log warnings c# +title: Triển khai logger tùy chỉnh C# trong GroupDocs.Redaction cho .NET +type: docs +url: /vi/net/advanced-redaction/custom-logging-groupdocs-redaction-net/ +weight: 1 +--- + +# Triển khai logger tùy chỉnh c# trong GroupDocs.Redaction cho .NET + +Quản lý việc xóa nhạy cảm tài liệu một cách hiệu quả là rất quan trọng, đặc biệt khi xử lý thông tin nhạy cảm. Trong hướng dẫn này, bạn sẽ học **cách triển khai một logger tùy chỉnh c#** với GroupDocs.Redaction cho .NET, cung cấp cho bạn quyền kiểm soát đầy đủ đối với việc ghi log, xử lý lỗi và theo dõi audit. + +## Câu trả lời nhanh +- **Logger tùy chỉnh c# làm gì?** Nó ghi lại các lỗi, cảnh báo và thông báo thông tin trong quá trình xóa nhạy cảm. +- **Thư viện nào cung cấp giao diện ILogger?** GroupDocs.Redaction for .NET. +- **Tôi có thể lưu tài liệu đã xóa nhạy cảm mà không rasterization không?** Có – sử dụng `redactor.Save(..., new Options.RasterizationOptions { Enabled = false })`. +- **Tôi có cần giấy phép cho việc sử dụng trong môi trường sản xuất không?** Cần giấy phép đầy đủ cho môi trường sản xuất; bản dùng thử có sẵn để đánh giá. +- **Phương pháp này có tương thích với .NET Core / .NET 6+ không?** Hoàn toàn – cùng một API hoạt động trên .NET Framework và .NET Core/5/6. + +## Logger tùy chỉnh c# là gì? +Một **logger tùy chỉnh c#** là một lớp triển khai giao diện `ILogger` do GroupDocs.Redaction cung cấp. Nó cho phép bạn chuyển hướng các thông điệp log tới bất kỳ nơi nào bạn cần—console, file, cơ sở dữ liệu, hoặc hệ thống giám sát bên ngoài—đồng thời cung cấp cho bạn cái nhìn rõ ràng về quy trình xóa nhạy cảm. + +## Tại sao nên sử dụng logging tùy chỉnh .net với GroupDocs.Redaction? +- **Tuân thủ & Kiểm toán:** Các log chi tiết đáp ứng các yêu cầu quy định. +- **Hiển thị lỗi:** `LogError` và `LogWarning` cung cấp phản hồi ngay lập tức về các vấn đề. +- **Tính linh hoạt tích hợp:** Chuyển tiếp log tới các framework logging .NET hiện có (Serilog, NLog, v.v.). + +## Yêu cầu trước +- **GroupDocs.Redaction for .NET** đã được cài đặt (xem phần cài đặt bên dưới). +- Môi trường phát triển .NET (Visual Studio, VS Code, hoặc CLI). +- Kiến thức cơ bản về C# và quen thuộc với các luồng file. + +## Cài đặt + +**.NET CLI** +```bash +dotnet add package GroupDocs.Redaction +``` + +**Package Manager** +```powershell +Install-Package GroupDocs.Redaction +``` + +**NuGet Package Manager UI** +Tìm kiếm **"GroupDocs.Redaction"** và cài đặt phiên bản mới nhất. + +## Đăng ký giấy phép +- **Dùng thử miễn phí:** Kiểm tra API với giấy phép tạm thời. +- **Giấy phép tạm thời:** Nhận quyền truy cập đầy đủ tính năng trong một thời gian giới hạn. +- **Mua:** Có được giấy phép vĩnh viễn cho triển khai sản xuất. + +## Hướng dẫn từng bước + +### Bước 1: Định nghĩa lớp logger tùy chỉnh (log cảnh báo c#) + +Tạo một lớp triển khai `ILogger`. Lớp này sẽ ghi lại các lỗi, cảnh báo và thông báo thông tin. + +```csharp +using System; +using GroupDocs.Redaction; + +class CustomLogger : ILogger +{ + public bool HasErrors { get; private set; } + + // Log errors encountered during processing. + public void LogError(string message) + { + Console.WriteLine("Error: " + message); + HasErrors = true; + } + + // Log warnings that may not be critical but need attention. + public void LogWarning(string message) + { + Console.WriteLine("Warning: " + message); + } + + // Log informational messages for tracking normal operations. + public void LogInfo(string message) + { + Console.WriteLine("Info: " + message); + } +} +``` + +**Giải thích:** Cờ `HasErrors` giúp bạn quyết định có tiếp tục xử lý hay không. Ba phương thức tương ứng với ba mức log bạn sẽ cần trong hầu hết các kịch bản xóa nhạy cảm. + +### Bước 2: Chuẩn bị đường dẫn file và mở tài liệu nguồn + +```csharp +string sourceFile = Utils.PrepareOutputDirectory("YOUR_DOCUMENT_DIRECTORY"); +string outputFile = Utils.GetOutputFile(sourceFile); +``` + +**Tại sao điều này quan trọng:** Sử dụng các phương thức tiện ích giúp mã của bạn sạch sẽ và đảm bảo thư mục đầu ra tồn tại trước khi bạn cố gắng **lưu tài liệu đã xóa nhạy cảm**. + +### Bước 3: Áp dụng xóa nhạy cảm khi sử dụng logger tùy chỉnh + +```csharp +using (Stream stream = File.Open(sourceFile, FileMode.Open, FileAccess.ReadWrite)) +{ + var logger = new CustomLogger(); + + using (Redactor redactor = new Redactor(stream, new LoadOptions(), new RedactorSettings(logger))) + { + // Apply a redaction to the document. + redactor.Apply(new DeleteAnnotationRedaction()); + + if (!logger.HasErrors) + { + using (Stream streamOut = File.Open(outputFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + // Save changes without rasterizing the output. + redactor.Save(streamOut, new Options.RasterizationOptions { Enabled = false }); + } + } + } +} +``` + +**Giải thích:** +1. `Redactor` được khởi tạo với `RedactorSettings(logger)`, liên kết `CustomLogger` của bạn. +2. Sau khi áp dụng một redaction, mã kiểm tra `logger.HasErrors`. Nếu không có lỗi nào xảy ra, tài liệu sẽ được lưu—điều này minh họa logic **lưu tài liệu đã xóa nhạy cảm** mà không cần rasterization. + +### Những cạm bẫy thường gặp & Khắc phục sự cố +- **Thiếu đầu ra log:** Xác minh rằng mỗi phương thức `Log*` đã được ghi đè đúng cách. +- **Ngoại lệ truy cập file:** Đảm bảo ứng dụng có quyền đọc/ghi cho cả đường dẫn nguồn và đầu ra. +- **Logger chưa được kết nối:** Tham số `RedactorSettings(logger)` là cần thiết; bỏ qua nó sẽ tắt logging tùy chỉnh. + +## Ứng dụng thực tiễn +1. **Báo cáo tuân thủ:** Xuất các mục log ra CSV hoặc cơ sở dữ liệu để tạo chuỗi audit. +2. **Theo dõi lỗi:** Nhanh chóng xác định các file có vấn đề bằng cách quét đầu ra `LogError`. +3. **Tự động hoá quy trình:** Kích hoạt các quy trình tiếp theo (ví dụ, thông báo cho nhân viên tuân thủ) khi `LogWarning` được gọi. + +## Các cân nhắc về hiệu năng +- **Giải phóng luồng kịp thời** để giải phóng bộ nhớ, đặc biệt khi xử lý các lô lớn. +- **Giám sát CPU & bộ nhớ** trong quá trình xóa nhạy cảm hàng loạt; cân nhắc xử lý tài liệu song song với việc đồng bộ logger cẩn thận. +- **Cập nhật thường xuyên:** Các phiên bản mới hơn của GroupDocs.Redaction thường bao gồm các tối ưu hoá hiệu năng và các hook logging bổ sung. + +## Kết luận + +Bằng cách triển khai một **logger tùy chỉnh c#**, bạn có được cái nhìn chi tiết về từng bước trong quy trình xóa nhạy cảm, giúp dễ dàng đáp ứng các tiêu chuẩn tuân thủ và gỡ lỗi. Phương pháp được trình bày ở đây hoạt động liền mạch với GroupDocs.Redaction cho .NET và có thể mở rộng để tích hợp với bất kỳ framework logging .NET nào bạn đã sử dụng. + +--- + +## Câu hỏi thường gặp + +**Q: Mục đích của logging tùy chỉnh với GroupDocs.Redaction là gì?** +A: Logging tùy chỉnh giúp theo dõi và quản lý các redaction để tuân thủ, theo dõi lỗi và tối ưu hoá quy trình làm việc. + +**Q: Làm thế nào để xử lý lỗi bằng logger tùy chỉnh?** +A: Triển khai `LogError` trong lớp `CustomLogger` của bạn; cờ `HasErrors` cho phép bạn dừng xử lý nếu cần. + +**Q: Logging tùy chỉnh có thể tích hợp với các hệ thống khác không?** +A: Có, bạn có thể chuyển tiếp các thông điệp log tới CRM, ERP, hoặc các công cụ giám sát trung tâm bằng cách mở rộng các phương thức logger. + +**Q: Một số cạm bẫy thường gặp khi triển khai logging tùy chỉnh là gì?** +A: Các triển khai phương thức không đúng, thiếu `RedactorSettings(logger)`, và vấn đề quyền truy cập file là những vấn đề phổ biến nhất. + +**Q: Logging tùy chỉnh cải thiện quy trình xóa nhạy cảm tài liệu như thế nào?** +A: Các log chi tiết cung cấp khả năng hiển thị thời gian thực, đơn giản hoá việc khắc phục sự cố và đáp ứng các yêu cầu audit. + +## Tài nguyên + +- **Tài liệu:** [GroupDocs.Redaction .NET Documentation](https://docs.groupdocs.com/redaction/net/) +- **Tham chiếu API:** [GroupDocs.Redaction API Reference](https://reference.groupdocs.com/redaction/net) +- **Tải xuống:** [GroupDocs.Redaction for .NET](https://downloads.groupdocs.com/redaction/net) + +--- + +**Cập nhật lần cuối:** 2026-03-28 +**Kiểm tra với:** GroupDocs.Redaction 23.11 for .NET +**Tác giả:** GroupDocs \ No newline at end of file