프로그래밍/Js

console.log 출력 내용을 <div>에 표시하는 방법

소행성왕자 2025. 2. 28. 18:04

웹 개발을 하다 보면 console.log()를 사용하여 디버깅해야 합니다.

하지만 모바일에서는 확인할 수 없어 불편할 때가 있습니다.

이 글에서는 console.log의 출력을 웹 페이지의 특정 <div> 영역에 표시하는 방법을 소개합니다.

기본적으로 console.log()는 브라우저의 개발자 도구에 출력됩니다.

하지만 이를 가로채서 웹 페이지 내의 <div>에 출력하도록 만들면, 개발자 도구 없이도 디버깅 정보를 쉽게 확인할 수 있습니다.

주요 기능:

  • console.log()의 기본 기능 유지
  • div 안에 로그 출력
  • 객체(Object)와 배열(Array) 변환하여 가독성 높이기
  • Promise 처리하여 해결된 값 출력
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Console Log to Div</title>
    <style>
        #log-container {
            width: 100%;
            height: 300px;
            border: 1px solid #ccc;
            padding: 10px;
            overflow-y: auto;
            background-color: #f9f9f9;
            font-family: monospace;
            white-space: pre-wrap; /* 줄바꿈 적용 */
        }
    </style>
</head>
<body>

    <h2>Console Output</h2>
    <div id="log-container"></div>

    <script>
        (function() {
            const oldConsoleLog = console.log;
            const logContainer = document.getElementById("log-container");

            console.log = function(...messages) {
                oldConsoleLog.apply(console, messages); // 원래 기능 유지

                messages.forEach((message) => {
                    const logMessage = document.createElement("div");

                    if (typeof message === "object") {
                        // Promise 처리
                        if (message instanceof Promise) {
                            message.then((resolvedValue) => {
                                logMessage.textContent = "Promise Resolved: " + JSON.stringify(resolvedValue, null, 2);
                                logContainer.appendChild(logMessage);
                            }).catch((error) => {
                                logMessage.textContent = "Promise Rejected: " + error;
                                logContainer.appendChild(logMessage);
                            });
                            return;
                        }

                        // 일반 객체 처리
                        logMessage.textContent = JSON.stringify(message, null, 2);
                    } else {
                        logMessage.textContent = message;
                    }

                    logContainer.appendChild(logMessage);
                });
            };
        })();

        // 테스트 로그
        console.log("Hello, World!");
        console.log({ name: "Alice", age: 25 });
        console.log([1, 2, 3, 4, 5]);

        const myPromise = new Promise((resolve) => setTimeout(() => resolve({ status: "success", data: [1, 2, 3] }), 1000));
        console.log(myPromise);
    </script>

</body>
</html>