Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy Standard Output và Standard Error Stream qua Console trong C#

Mục đích

Thuộc tính Console.Out và Console.Error trả về TextWriter đại diện cho **standard output** (stdout) và **standard error** (stderr). Cho phép redirect, ghi log riêng biệt.

Ví dụ 1: Standard Output Stream

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Console.WriteLine($"Standard Output Stream: {Console.Out}");
        // Output: System.IO.TextWriter+SyncTextWriter
    }
}

Ví dụ 2: Cả Output và Error Stream

using System;

public class Demo
{
    public static void Main(string[] args)
    {
        Console.WriteLine($"Standard Output: {Console.Out}");
        Console.WriteLine($"Standard Error: {Console.Error}");

        // Ghi trực tiếp vào Error stream
        Console.Error.WriteLine("Đây là thông báo lỗi (stderr)");
        Console.Out.WriteLine("Đây là output bình thường (stdout)");
    }
}

Kết quả (chạy bình thường)

Standard Output: System.IO.TextWriter+SyncTextWriter
Standard Error: System.IO.TextWriter+SyncTextWriter
Đây là thông báo lỗi (stderr)
Đây là output bình thường (stdout)

Ứng dụng: Redirect Stream

using System;
using System.IO;

public class Demo
{
    public static void Main()
    {
        // Redirect stdout ra file
        using (var sw = new StreamWriter("stdout.log"))
        {
            Console.SetOut(sw);
            Console.WriteLine("Dòng này ghi vào file stdout.log");
        }

        // Redirect stderr ra file khác
        using (var sw = new StreamWriter("stderr.log"))
        {
            Console.SetError(sw);
            Console.Error.WriteLine("Dòng này ghi vào file stderr.log");
        }

        // Khôi phục mặc định
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
        Console.SetError(new StreamWriter(Console.OpenStandardError()) { AutoFlush = true });

        Console.WriteLine("Đã khôi phục console.");
    }
}

Lưu ý

  • Console.Out và Console.Error mặc định cùng trỏ đến console window.
  • Khi chạy trong IDE/terminal, stderr thường hiển thị cùng màu hoặc có thể lọc riêng (ví dụ: 2> error.log trong bash/cmd).
  • Dùng Console.SetOut/SetError để redirect toàn ứng dụng.
  • TextWriter có AutoFlush - bật để ghi ngay lập tức.

So sánh với Console.WriteLine

  • Console.WriteLine -> ghi vào Console.Out (stdout).
  • Console.Error.WriteLine -> ghi vào Console.Error (stderr).
  • Best practice: Thông báo lỗi, log debug -> stderr. Kết quả chương trình -> stdout.