← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 5 of 12

Logging कैसे करें

Logging आपके script ने क्या किया इसकी एक diary रखने जैसा है, हर entry के बगल में समय लिखा हुआ, ताकि आप बाद में वापस पढ़ सकें और समझ सकें कि क्या हुआ था।

In this page:

  1. Logging
Syntax
bash
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}
log "message"

Logging

एक simple logging function जो messages को एक timestamp के साथ prefix करता है scripts को debug करना scattered echo calls से कहीं ज़्यादा आसान बनाता है।

Logs को tee या redirection से एक file में भेजना आपको script खत्म होने के बाद यह review करने देता है कि क्या हुआ था। Consistent logging खासकर उन scripts में valuable है जो unattended run होते हैं, जैसे cron jobs।

Note: हर log line में एक timestamp शामिल करें ताकि आप script के behavior को system में कहीं और होने वाले events के साथ correlate कर सकें।

उदाहरण: Logging

bash
#!/bin/bash
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

log "Script started"
log "Processing data..."
log "Script finished"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Logs को > से लिखना इसलिए file हर बार overwrite हो जाती है; >> उपयोग करें।
  2. 2>&1 के बिना errors और output को mix करना।
  3. Timestamps के बिना logging करना, जो problems को trace करना मुश्किल बनाता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.